how to inherit __init__ attributes from parent class to __init__ in the child class?

Viewed 53

I'm trying to inherit the attributes from parent class:

class Human:
def __init__(self,name,date_of_birth,gender,nationality):
    self.name = name
    self.date_of_birth = date_of_birth
    self.gender = gender
    self.nationality = nationality

To the child class Student:

class Student(Human):
def __init__(self,university,std_id,first_year_of_registration,study_program):
    super(Student,self).__init__(name,date_of_birth,gender,nationality)
    self.university = university
    self.std_id = std_id
    self.first_year_of_registration = first_year_of_registration
    self.study_program = study_program


def select(c):
    pass
def drop(c):
    pass

def __str__(self):
    return 'Student ID {self.std_id},and student name is {self.name} and his study program is {self.study_program}'.format(self=self)

So i can create an object using both (parent,student) attributes like So:

s = Student('mark','2000-1-1','M','country','school',2017159,2017,'SE')

then i can:

print(s)

and invoke __str__ function like so:

Student ID 2017159,and student name is mark and his study program is SE

but whenever i create the object it give me error:

Traceback (most recent call last):
Python Shell, prompt 7, line 1
builtins.TypeError: __init__() takes 5 positional arguments but 9 were 
given

i'm new to python. So i searched the internet and tried to do like some of the inheritance examples, like so:

Human.__init__()

but nothing worked, also i checked many answers here but none of them solved my problem. hope anyone can help and point out what is wrong here.

1 Answers
def __init__(self,university,std_id,first_year_of_registration,study_program)

but

Student('mark','2000-1-1','M','country','school',2017159,2017,'SE')

?

Well, you see, Python is not a mind-reader. You need to tell it what you want.

Right now Python wants all and only university,std_id,first_year_of_registration,study_program, nothing more, nothing less.

This means, you need to tell it to get other elements:

class Student(Human):
    def __init__(self,name,date_of_birth,gender,nationality, university,std_id,first_year_of_registration,study_program):
        ...

or by saying "and get some other elements". But remember! Those other elements must be at the end of the constructor!

class Student(Human):
    def __init__(self,university,std_id,first_year_of_registration,study_program, *args, **kwargs):
        super(Student,self).__init__(*args, **kwargs)
        ...

It basically catches all positional arguments (args) and keyword arguments (kwargs) and passes them further.

As I said, it only takes argument from the end, so you need to do:

Student('school',2017159,2017,'SE', 'mark','2000-1-1','M','country')

The way interpreter sees it, it will take 1st argument and put it in university, then 2nd in std_id... up to study_program, and then put the rest in the list args.

Related