I know that I can inherit handpicked variables from a parent class by adding their name in a super() function as follows:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("myfirstname", "andlast")
But I need to do two other things:
So, what am I supposed to write for the above tasks?
The __init__ is a regular function, and has the same capabilities as any other – use *args and **kwargs to forward arguments anonymously. Additional parameters can be defined explicitly to not pass them on and allow using them directly.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
class Student(Person):
# *args/**kwargs receive unspecified arguments
def __init__(self, *args, semester, **kwargs):
# v pass on any unspecified arguments
super().__init__(*args, **kwargs)
# v use explicitly specified argument
self.semester = semester
x = Student("myfirstname", "andlast", semester=6)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With