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

后端 未结 15 2590
無奈伤痛
無奈伤痛 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:50

    Python also has super as well:

    super(type[, object-or-type])

    Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

    Example:

    class A(object):     # deriving from 'object' declares A as a 'new-style-class'
        def foo(self):
            print "foo"
    
    class B(A):
        def foo(self):
            super(B, self).foo()   # calls 'A.foo()'
    
    myB = B()
    myB.foo()
    

提交回复
热议问题