的Python:自动调用父功能子实例化后
的Python 2.7的Python:自动调用父功能子实例化后
我想automotically调用父对象的功能我实例化后,其子
class Mother:
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
# desired behavior
>>> billy = Child()
hi mom
hello son
有没有一种方法可以让我做这个?
编辑,从下面的注释:
“我应该做它在我的问题更清晰,我真正想要的是某种形式的‘自动’调用父类的方法通过的实例化单独触发孩子,没有明确地从孩子那里调用父母的方法,我希望能有这种神奇的方法,但我不认为有这种方法。“
使用super()
?
class Child(Mother):
def __init__(self):
print 'hi mom'
super(Child, self).call_me_maybe()
由于OP似乎使用Python 2,他不能使用方便的'super()'。 2.x版本将是'super(Child,self).call_me_maybe()'。 –
@HannesOvrén:你怎么知道OP使用Python 2? – cdarke
@cdarke从他们的'print'语句 –
你可以使用super
,但你应该设置你的超从object
继承:
class Mother(object):
# ^
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
super(Child, self).call_me_maybe()
>>> billy = Child()
hi mom
hello son
由于子类继承了父母的方法,你可以简单地调用__init__()
声明中的方法。
class Mother(object):
def __init__(self):
pass
def call_me_maybe(self):
print('hello son')
class Child(Mother):
def __init__(self):
print('hi mom')
self.call_me_maybe()
虽然这是做同样的事情,OP的请求是你调用父方法。使用'super'可以帮助他们知道他们也可以用这种技术调用父母的'__init__'。 –
您正在使用哪个版本的python? – cdarke