简体   繁体   中英

Python overriden methods called from superclass

There are lot of information about mangling and it's usage, however I am struggling to understand the following piece of code:

class Parent:

    NAME = 'PARENT'

    def __init__(self):
      self.print_me()

    def print_me(self):
      print(f"Parent class {self.NAME}")


class Child(Parent):

    NAME = 'CHILD'

    def __init__(self):
      super().__init__()

    def print_me(self):
      print(f"Child class {self.NAME}")


c = Child()

Can someone please explain how the overriden method (print_me) is called from the parent class init and does not print Parent class PARENT? If I use mangling both for NAME and print_me the method is not overriden and thus it's called from the parent which is expected.

Here the object(c) is child class object In child class the constructor calls the parent class and the parent class constructor calls the print_me method Here you called the child object so it will execute the child method. If the print_me method is not available in child then it will execute parent method

If you needed it to print the parent function, you should instead create the parent object.

c = Parent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM