kroetnaton
kroetnaton

Reputation: 17

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.

Upvotes: 0

Views: 277

Answers (2)

PrefixEt
PrefixEt

Reputation: 183

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.

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36033

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, i.e. _slave, fixes your problem while still indicating to users that this is a 'private' API that they should avoid touching.

Upvotes: 3

Related Questions