Skip to main content
 首页 » 编程设计

Python:子实例化后自动调用父函数

2025年05月04日17bhlsheji

python 2.7

我想在实例化它的子对象后自动调用父对象的函数

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 

我有办法做到这一点吗?

编辑,来自下面的评论:

“我应该在我的问题中说得更清楚,我真正想要的是某种仅由子实例化触发的父方法的‘自动’调用,而不是从 child 。我希望对此有某种神奇的方法,但我认为没有。”

请您参考如下方法:

你可以使用 super但是你应该将你的父类(super class)设置为从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