How to call a Parent Class's method from Child Class in Python?

后端 未结 15 2582
無奈伤痛
無奈伤痛 2020-11-22 10:14

When creating a simple object hierarchy in Python, I\'d like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:44

    I would recommend using CLASS.__bases__ something like this

    class A:
       def __init__(self):
            print "I am Class %s"%self.__class__.__name__
            for parentClass in self.__class__.__bases__:
                  print "   I am inherited from:",parentClass.__name__
                  #parentClass.foo(self) <- call parents function with self as first param
    class B(A):pass
    class C(B):pass
    a,b,c = A(),B(),C()
    

提交回复
热议问题