如何在python中使用子类的方法调用第二个父类的方法?

时间:2016-08-05 12:31:52

标签: python python-2.7 python-3.x ipython multiple-inheritance

以下是我的代码:

class Parent1(object):
    def __init__(self):
        print "!!! ___initialization Parent1___ !!!"

    def method(self):
        print "*** method of Parent1 is called ***"


class Parent2(object):
    def __init__(self):
        print "!!! ___initialization Parent2___ !!!"

    def method(self):
        print "*** method of Parent2 is called ***"

class Child(Parent1,Parent2):
    def __init__(self):
        print "!!! ___initialization Child___ !!!"

    def method(self):
        super(Child,self).method()
        print "*** method of Child is called ***"


Ch = Child()
Ch.method()

我想使用子类的对象调用method()类的Parent2。条件只应创建子类对象,子类声明中不得更改(class Child(Parent1,Parent2):不应更改。)

1 个答案:

答案 0 :(得分:1)

Parent2.method(self)

这就是你需要的全部 - instance.method()只是ClassName.method(instance)的语法糖,所以你需要做的就是在没有语法糖的情况下调用它并且它会做得很好

我将Child类更改为:

class Child(Parent1,Parent2):
    def __init__(self):
        print "!!! ___initialization Child___ !!!"

    def method(self):
        super(Child,self).method()
        print "*** method of Child is called ***"
        Parent2.method(self)

# Out:
$ python c.py
!!! ___initialization Child___ !!!
*** method of Parent1 is called ***
*** method of Child is called ***
*** method of Parent2 is called ***

您可以完美地获得预期的输出。