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

后端 未结 15 2594
無奈伤痛
無奈伤痛 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:57

    Many answers have explained how to call a method from the parent which has been overridden in the child.

    However

    "how do you call a parent class's method from child class?"

    could also just mean:

    "how do you call inherited methods?"

    You can call methods inherited from a parent class just as if they were methods of the child class, as long as they haven't been overwritten.

    e.g. in python 3:

    class A():
      def bar(self, string):
        print("Hi, I'm bar, inherited from A"+string)
    
    class B(A):
      def baz(self):
        self.bar(" - called by baz in B")
    
    B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"
    

    yes, this may be fairly obvious, but I feel that without pointing this out people may leave this thread with the impression you have to jump through ridiculous hoops just to access inherited methods in python. Especially as this question rates highly in searches for "how to access a parent class's method in Python", and the OP is written from the perspective of someone new to python.

    I found: https://docs.python.org/3/tutorial/classes.html#inheritance to be useful in understanding how you access inherited methods.

提交回复
热议问题