2

I have two classes. Where the Parent class has some default values. I would like the Child class to inherit the init() method of the Parent class and also the default values.

However, when I try to change the values of the optional arguments, I can't do it. For example, in the code below, I can't change the value of year_born.

def get_current_age(x):
    return 2017-x
get_age = get_current_age

class Parent():
    def __init__(self,name,last_name, siblings=0, year_born=1900, age=get_age):
        self.name = name
        self.last_name = last_name
        self.siblings = siblings
        self.year_born=year_born
        self._get_age = get_age(self.year_born)

class Child(Parent):
    def __init__(self,name,last_name, siblings=0, year_born=1900, age=get_age):
        super().__init__(name,last_name, siblings=0, year_born=1900, age=get_age)
        self.lives_with_parent= True
        self.stil_in_school= None

When I create instances of the Parent class with the default values, the output is ok. When I create a Child instance with a different value for age, it still takes the default value.

Dad=Parent('Fyodr','Dosto')
print('Dad is' ,Dad._get_age)

kid = Child('Joseph','Dosto', year_born=2000)
print('Kid is' ,kid._get_age)

Dad is 117
Kid is 117

I don't know if you have any other ideas of how to fix this or write it in a better way. Many thanks,

3
  • 1
    Well, you called super().__init__(stuff, year_born=1900, ...). What did you expect?? Commented Dec 29, 2017 at 16:41
  • 2
    That super call is wrong. It should be super().__init__(name,last_name, siblings, year_born, age) Commented Dec 29, 2017 at 16:42
  • Thank you @pm-2ring The init__(self,name,last_name, siblings=0, year_born=1900, age=get_age) of the Child should contain the defaults, but not super().__init_ ? Commented Dec 29, 2017 at 16:44

1 Answer 1

3

Change this line in Child class:

super().__init__(name,last_name, siblings, year_born, age=get_age)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that works. I now see that the defaults should not bee in the call of the super().__init__ function but only in the definition. 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.