Search code examples
pythoninheritancedefaultinitsuper

How to inherit default values from Parent class using super()


fairly new to python here, and to programming as general, i have the following example, in which i'm trying to inherit the default values from the Parent class, in a way that both the objects can be made. How to do it nicely and clean? - Tried to experiment with *args and **kwargs, but it had different errors.

class Person(object):

def __init__(self, name="Jane Doe", age="30", gender="female"):
    self.name = name
    self.age = age
    self.gender = gender
    self.goal = "My goal is: Live for the moment!"


class Student(Person):

def __init__(self, name, age, gender, prev_org="The School of Life", skip_d=0):
    super(Student, self).__init__(name, age, gender,)
    self.prev_org = prev_org
    self.skip_d = skip_d
    self.goal = "Be a junior software developer."

 john = Student('John Doe', 20, 'male', 'BME')

 student = Student()

Solution

  • I don't think this is possible. What I've seen instead is something like this:

    class Person(object):
    
        def __init__(self, name=None, age=None, gender=None):
            if name is None:
                name = "Jane Doe"
            if age is None:
                age = "30"
            if gender is None:
                gender = "female"
    
            self.name = name
            self.age = age
            self.gender = gender
            self.goal = "My goal is: Live for the moment!"
    
    
    class Student(Person):
    
        def __init__(self, name=None, age=None, gender=None, prev_org="The School of Life", skip_d=0):
            super(Student, self).__init__(name, age, gender)
            self.prev_org = prev_org
            self.skip_d = skip_d
            self.goal = "Be a junior software developer."
    
    
    john = Student('John Doe', 20, 'male', 'BME')
    
    student = Student()