Reputation: 59
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()
Upvotes: 1
Views: 2039
Reputation: 2470
You can achieve this with *args
, but I don't think it's a great design choice.
class Student(Person):
def __init__(self, *args, prev_org="The School of Life", skip_d=0):
super(Student, self).__init__(*args[:2])
This is passing the first 3 positional arguments off to the parent (Person
) class so Student
doesn't need to worry about it.
You need to slice ([:2]
) the list because if you create an instance of Student
like so:
john = Student('John Doe', 20, 'male', 'BME')
Then 'BME'
is now a positional argument, and is included in *args
. Whereas:
john = Student('John Doe', 20, 'male', prev_org='BME')
It is now a keyword argument, so wouldn't appear in *args
.
Upvotes: 1
Reputation: 662
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()
Upvotes: 0