Search code examples
pythonpython-3.xinheritancesupermagic-methods

Method with same name in Derived class wrongly called in Parent class while using inheritance in Python


I have the following code

class Parent(bytes):
    def __init__(self, validate=True):
        super().__init__()
        if validate:
            self.validate()

    def validate(self):
        print("Validation of Parent")
        return self

class Derived(Parent):
    def __init__(self, validate=True):
        super().__init__()
        if validate:
            self.validate()

    def validate(self):
        print("Validation of Derived")
        return self

object = Derived()

It is also required that init() has to be called in Derived to unpack different types of data. Also validate=True has to be passed into init() as argument and this part has to stay to avoid flake8 & pylint warning check:

if validate:
    self.validate()

And my current output is:

Validation of Derived
Validation of Derived

But I want expected output to be:

Validation of Parent
Validation of Derived

Is there a way to modify how the validate() method is called in Parent class to avoid this error?


Solution

  • Since the Parent class __init__() already calls validate() your derived class need not. But, your version of validate should:

    class Parent(bytes):
        def __init__(self, validate=True):
            super().__init__()
            if validate:
                self.validate()
    
        def validate(self):
            print("Validation of Parent")
            return self
    
    class Derived(Parent):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # do specialised setup here.
    
        def validate(self):
            super().validate()
            print("Validation of Derived")
            return self
    
    object = Derived()
    

    Output as expected.

    Update: Just be aware that I've shown the call to super().__init__() first, which, of course calls down to your validate(). You may actually need to perform the specialised setup first and then do the super call to init.