不能调用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) –