【问题标题】:How to call method of second parent class using method of child class in python?如何在python中使用子类的方法调用第二个父类的方法?
【发布时间】:2016-12-11 21:01:07
【问题描述】:

下面是我的代码:

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

我想使用子类的对象调用Parent2 类的method()。条件是只有子类对象应该被创建并且子类声明没有变化(class Child(Parent1,Parent2):应该不会改变。)

【问题讨论】:

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


    【解决方案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 ***
    

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

    【讨论】:

    • 你也可以把super(Child, self).method()改成Parent1.method(self)。此类层次结构并非旨在正确使用super
    • @James:感谢您的解决方案。这是唯一的方法吗?还有其他方法吗?不能用super()或者decorator来完成吗?
    • @Praveenkumar 我不知道,但我绝不是 Python 继承方面的专家,可能有一些我不知道的方法。
    • 感谢@James 的解决方案。
    • @詹姆斯。行,我会的。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2022-01-16
    • 2014-08-24
    • 2011-09-04
    相关资源
    最近更新 更多