Python 多重继承示例
Python Multiple Inheritance Example
我有这种情况
class A(object):
def __init__(self):
self.x = 0
self.y = 0
class B(A):
def __init__(self):
super(B, self).__init__()
def method(self):
self.x += 1
class C(A):
def __init__(self):
super(C, self).__init__()
def method(self):
self.y += 1
class D(B, C):
def __init__(self):
super(D, self).__init__()
def method(self):
print self.x
print self.y
我希望 D 为 x 和 y 都打印 1,但它正在打印 0。
我不完全理解多个 inheritance/super/etc...虽然我一直在尝试阅读文档,但对示例的解释对我很有帮助。
谢谢!
创建 D 对象时,它永远不会调用名为 'method' 的方法。
它只会调用父级的“init”方法。所以 x 或 y 不会改变。
如果您在您的示例中重写了类似 method
的方法,但仍希望获得基础 class 以及您自己的行为,则需要使用 super
调用您要覆盖的方法的版本。
class A(object):
def __init__(self):
self.x = 0
self.y = 0
def method(self): # we need a verion of method() to end the super() calls at
pass
class B(A):
def method(self):
super(B, self).method() # call overridden version of method()
self.x += 1
class C(A):
def method(self):
super(C, self).method() # here too
self.y += 1
class D(B, C):
def method(self):
super(D, self).method() # and here
print self.x
print self.y
我已经删除了您 child class 中不必要的 __init__
方法。除非您要更改方法的行为,否则无需重写方法,并且 none 后来的 __init__
方法除了调用其前身之外还做了任何事情。
您还可以在 D subclass 中调用继承的 classes 的方法
class D(B, C):
def __init__(self):
B.__init__(self)
C.__init__(self)
def method(self):
B.method(self)
C.method(self)
print(self.x)
print(self.y)
我有这种情况
class A(object):
def __init__(self):
self.x = 0
self.y = 0
class B(A):
def __init__(self):
super(B, self).__init__()
def method(self):
self.x += 1
class C(A):
def __init__(self):
super(C, self).__init__()
def method(self):
self.y += 1
class D(B, C):
def __init__(self):
super(D, self).__init__()
def method(self):
print self.x
print self.y
我希望 D 为 x 和 y 都打印 1,但它正在打印 0。
我不完全理解多个 inheritance/super/etc...虽然我一直在尝试阅读文档,但对示例的解释对我很有帮助。
谢谢!
创建 D 对象时,它永远不会调用名为 'method' 的方法。 它只会调用父级的“init”方法。所以 x 或 y 不会改变。
如果您在您的示例中重写了类似 method
的方法,但仍希望获得基础 class 以及您自己的行为,则需要使用 super
调用您要覆盖的方法的版本。
class A(object):
def __init__(self):
self.x = 0
self.y = 0
def method(self): # we need a verion of method() to end the super() calls at
pass
class B(A):
def method(self):
super(B, self).method() # call overridden version of method()
self.x += 1
class C(A):
def method(self):
super(C, self).method() # here too
self.y += 1
class D(B, C):
def method(self):
super(D, self).method() # and here
print self.x
print self.y
我已经删除了您 child class 中不必要的 __init__
方法。除非您要更改方法的行为,否则无需重写方法,并且 none 后来的 __init__
方法除了调用其前身之外还做了任何事情。
您还可以在 D subclass 中调用继承的 classes 的方法 class D(B, C):
def __init__(self):
B.__init__(self)
C.__init__(self)
def method(self):
B.method(self)
C.method(self)
print(self.x)
print(self.y)