简体   繁体   中英

How do I call the overwritten method of the child class instead of the parent class method?

So I have the parent class parent:

class Parent:
    def master(self):
       self.__slave()
    def __slave(self):
        print('No!')

And the child class child:

class Child(Parent):
    def __slave(self):
        print('Yay!')

But whenever I call child.master() it uses the __slave of Parent. Is there any way I can let it use the overwritten method of Child if I call it from Child? Because with this code I only get 'No.'s.

Don't use double underscore ( __ ) for methods that you want to override, as it does name mangling specifically for the purpose of not clashing with child classes.

From the documentation :

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:

Using a single underscore, ie _slave , fixes your problem while still indicating to users that this is a 'private' API that they should avoid touching.

This is due to the use of double underscore in front of the method name. The python interpreter does not see the child class method since it is private.

class Parent:
    def master(self):
       self._slave()
    def _slave(self):
        print('No!')

class Child(Parent):
    def _slave(self):
        print('Yay!')

Child().master()

Try this.

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