Home > database >  How to access method parameter of inherited class in python
How to access method parameter of inherited class in python

Time:07-26

I try to add some functionality to an inherited method "represent" from a Person class by updating a dictionary with attributes of chid class.

However, it gives me an error which says name 'person_info' is not defined.

How can I fix it?

Thanks in advance!

class Person:
    def __init__(self, first_name, last_name, date_of_birth):
        self.first_name = first_name,
        self.last_name = last_name,
        self.date_of_birth = date_of_birth

    def calculate_age(self):
        today = date.today()
        current_age = today.year - self.date_of_birth.year - \
                      ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
        return current_age

    def represent(self):
        person_info = dict({'first_name': self.first_name[0],
                            'last_name': self.last_name[0],
                            'date_of_birth': self.date_of_birth})
        return person_info


class Student(Person):
    def __init__(self, first_name, last_name, date_of_birth, course, grade):
        super().__init__(first_name, last_name, date_of_birth)
        self.course = course
        self.grade = grade
        
    def represent(self):
        super().represent()
        person_info

CodePudding user response:

You can try like this as said by @DeepSpace in the comment...

class Student(Person):
    def __init__(self, first_name, last_name, date_of_birth, course, grade):
        super().__init__(first_name, last_name, date_of_birth)
        self.course = course
        self.grade = grade
    
    def represent(self):
       person_info = super().represent()
       person_info['grade'] = self.grade
       person_info['course'] = self.course

       return person_info
  • Related