Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inherit all variable from a parent class to a base class having an init function?

Tags:

python

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:

  1. Inherit all the attributes from the parent class without mentioning each's name, so I can just call them as self.attrbname.
  2. After doing no.1, add more attributes in the child class through the init function.

So, what am I supposed to write for the above tasks?

like image 541
Ashrafsk Avatar asked Nov 18 '25 23:11

Ashrafsk


1 Answers

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)
like image 163
MisterMiyagi Avatar answered Nov 20 '25 13:11

MisterMiyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!