Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在子实例化后自动调用父函数_Python_Oop_Inheritance_Python Object - Fatal编程技术网

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

Python:在子实例化后自动调用父函数,python,oop,inheritance,python-object,Python,Oop,Inheritance,Python Object,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 >>> bil

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
我有办法做到这一点吗

从下面的评论中编辑:

“在我的问题中,我应该说得更清楚一些,我真正想要的是完全由子对象的实例化触发的对父对象方法的某种‘自动’调用,而不是从子对象显式调用父对象方法。我希望有某种神奇的方法来实现这一点,但我认为没有。”使用
super()

可以使用,但应将超类设置为从
对象继承:

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()


由于子类继承了父类方法,因此您只需在
\uuuu init\uuuu()
语句中调用该方法即可

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似乎使用Python 2,所以他不能使用方便的
super()
。2.x版本将是超级版(儿童,自我)。call_me_maybe()
@hannesovren:你怎么知道OP使用的是Python 2?@cdarke从他们的
打印
声明中,@cdarke说:)另外,他关于
母亲的观点也很重要。@MosesKoledoye:我没听清楚。我查看了OP的历史,发现了一个Python3问题。您使用的是哪一版本的python?尽管这做了同样的事情,OP的要求是您调用父方法。使用
super
可以帮助他们知道也可以使用此技术调用父级的
\uuuu init\uuuu
>>> billy = Child()
hi mom
hello son
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()