Home > Mobile >  python inheritance of class that have init argument
python inheritance of class that have init argument

Time:01-08

class Salary:
    def __init__(self, basic_salary_table):
        self.basic_salary_table = basic_salary_table
        pass

    def basic_salary(self):
        if self.grade == 0:
            if self.level > 50:
                return int(self.basic_salary_table[3][self.basic_salary_table[3]['level']==50]['basic_salary'])
            return int(self.basic_salary_table[3][self.basic_salary_table[3]['level']==self.level]['basic_salary'])
        else:
            self.grade = str(self.grade) 'grade'
            return int(self.basic_salary_table[0][self.basic_salary_table[0]['level']==self.level][self.grade])

class Person(Salary):
    def __init__(self, name, id, job, level, grade=0):
        self.name = name
        self.id = id
        self.job = job
        self.level = level
        self.grade = grade

when i create Person object as person1 then call person1.basic_salary() interpreter says, 'Person' object has no attribute 'basic_salary_table'

CodePudding user response:

You need to execute super().__init__ method in __init__ method of subclass.

object.__init__

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).

Like this:

class A:

    def __init__(self, a):
        self.a = a

    def print_a(self):
        print(self.a)


class B(A):

    def __init__(self, a, b):
        self.b = b
        super().__init__(a)


B(1, 2).print_a()

# 1
  •  Tags:  
  • Related