不能調用GParent的testmethod
無GParent
實例作爲其第一個參數。
繼承
class GParent(object):
def testmethod(self):
print "I'm a grandpa"
class Parent(GParent):
# implicitly inherit __init__()
# inherit and override testmethod()
def testmethod(self):
print "I'm a papa"
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
# You can only call testmethod with an instance of Child
# though technically it is calling the parent's up the chain
self.testmethod()
# inherit parent's testmethod implicitly
c = Child() # print "I'm a papa"
但是,調用父母的方法明確地兩種方式是通過組合物或類方法
組成
class Parent(object):
def testmethod(self):
print "I'm a papa"
class Child(object):
def __init__(self):
self.parent = Parent()
# call own's testmethod
self.testmethod()
# call parent's method
self.parentmethod()
def parentmethod(self):
self.parent.testmethod()
def testmethod(self):
print "I'm a son"
c = Child()
類方法
class Parent(object):
@classmethod
def testmethod(cls):
print "I'm a papa"
class Child(object):
def __init__(self):
# call own's testmethod
self.testmethod()
# call parent's method
Parent.testmethod()
def testmethod(self):
print "I'm a son"
c = Child()
由於繼承對父類創建依賴關係,所以在處理多重繼承時已經開始使用組合了。
你的'Parent'和'Child'不是從'GParent'繼承的。你打算這麼做嗎? – BrenBarn
可能重複[在Python中從子類調用父類的方法?](http://stackoverflow.com/questions/805066/call-a-parent-classs-method-from-child-class-in-python) –