0

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.

1
  • Your Child class constructor has to call the Parent class constructor. super(Child, self).__init__() Commented May 25, 2022 at 16:00

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

'**kwargs' in the 'init' method is exactly what it takes! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.