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

后端 未结 15 2595
無奈伤痛
無奈伤痛 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 11:03

    In Python 2, I didn't have a lot luck with super(). I used the answer from jimifiki on this SO thread how to refer to a parent method in python?. Then, I added my own little twist to it, which I think is an improvement in usability (Especially if you have long class names).

    Define the base class in one module:

     # myA.py
    
    class A():     
        def foo( self ):
            print "foo"
    

    Then import the class into another modules as parent:

    # myB.py
    
    from myA import A as parent
    
    class B( parent ):
        def foo( self ):
            parent.foo( self )   # calls 'A.foo()'
    

提交回复
热议问题