Home > Software engineering >  override multiple attributes inherited from parent class in Python
override multiple attributes inherited from parent class in Python

Time:05-26

I'd like to assign different values to inherited attributes in the instances of a child class. The code I use is

class Parent:
    def __init__(self, n=50):
        # there are multiple parent attributes like 'n'
        # I use just one to reproduce the error
        self.n = n
        
    def print_n(self):
        print('n =', self.n)
        
class Child(Parent):
    def __init__(self, a=5):
        self.a = a
        
    def print_a(self):
        print('a =', self.a)
      
son1 = Child(n=100)
son1.print_n() 

The error message is

son1 = Child(n=100)

TypeError: __init__() got an unexpected keyword argument 'n'

What would be the correct way to achieve the objective?

I tried to put super().init() in the init method of the child class according to the answer to this similar question, but it didn't work.

CodePudding user response:

Your Child.__init__ needs to call Parent.__init__ explicitly; it won't happen automagically. If you don't want Child.__init__ to have to "know" what Parent.__init__'s args are, use *args or in this case **kwargs to pass through any kwargs that aren't handled by Child.__init__.

class Parent:
    def __init__(self, n=50):
        # there are multiple parent attributes like 'n'
        # I use just one to reproduce the error
        self.n = n
        
    def print_n(self):
        print('n =', self.n)
        
class Child(Parent):
    def __init__(self, a=5, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.a = a
        
    def print_a(self):
        print('a =', self.a)
      
son1 = Child(n=100)
son1.print_n()
  • Related