Home > Enterprise >  Use default values for attributes in child class in Python
Use default values for attributes in child class in Python

Time:04-12

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'

CodePudding user response:

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')

  • Related