python 继承 class 具有 init 参数
python inheritance of class that have init argument
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
当我将 Person 对象创建为 person1 然后调用 person1.basic_salary()
解释器说,'Person' 对象没有属性 'basic_salary_table'
您需要在子类的__init__
方法中执行super().__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...])
.
像这样:
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
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
当我将 Person 对象创建为 person1 然后调用 person1.basic_salary() 解释器说,'Person' 对象没有属性 'basic_salary_table'
您需要在子类的__init__
方法中执行super().__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...])
.
像这样:
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