1

I have a Person class in Python

class Person:
    def __init__(self, name='Sam', phone=456):
        self.name = name
        self.phone = phone

and a teenager class which inherits from Person :

class Teenager(Person):
        def __init__(self, name, phone,website):
            super().__init__(name, phone)
            self.website = website

Is there a way to instantiate a Teenager object using default values from Person class for name and phone without declaring them again in Teenarger class ?

When I try :

teen = Teenager(website='www.example.com')

I got this error :

TypeError: __init__() missing 2 required positional arguments: 'name' and 'phone'
2
  • Thanks, I modified the code but I get still the same error Commented Apr 11, 2022 at 16:59
  • Inheritance aside, you can't have a non-default argument (website) follow default arguments (name and phone), so you can't have Teenager's args be name, phone, website if you want name and phone to be optional. Commented Apr 11, 2022 at 17:06

1 Answer 1

3
class Teenager(Person):
        def __init__(self, website, **kwargs):
            super().__init__(**kwargs)
            self.website = website

teen = Teenager(website='www.example.com')
# or just
teen = Teenager('www.example.com')

Sign up to request clarification or add additional context in comments.

Comments

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.