如何让subclass中的constructor继承constructor或baseclass?
How to let the constructor in the subclass inherit the constructor or base class?
我有以下代码段,其输出如下所示
from abc import ABCMeta, abstractmethod
class AbstractClass(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self, n):
self.n = n
print('the salary information')
class Employee(AbstractClass):
def __init__(self, salary, name):
self.salary = salary
self.name = name
super(AbstractClass,self).__init__()
emp1 = Employee(1000000, "Tom")
print(emp1.salary)
print(emp1.name)
我想让子类,例如Employee
,也可以继承AbstractClass
的构造函数中实现的功能。具体来说,我添加的print('the salary information')
:
super(AbstractClass,self).__init__() # which does not work
您需要将 CURRENT class 传递给 super
,而不是 parent。所以:
super(Employee,self).__init__()
Python 会找出调用哪个 parent class。
当你这样做时,它不会起作用,因为 AbstractClass.__init__
需要一个你没有提供的额外参数。
跟进
已正确指出这就足够了:
super().__init__(0)
我有以下代码段,其输出如下所示
from abc import ABCMeta, abstractmethod
class AbstractClass(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self, n):
self.n = n
print('the salary information')
class Employee(AbstractClass):
def __init__(self, salary, name):
self.salary = salary
self.name = name
super(AbstractClass,self).__init__()
emp1 = Employee(1000000, "Tom")
print(emp1.salary)
print(emp1.name)
我想让子类,例如Employee
,也可以继承AbstractClass
的构造函数中实现的功能。具体来说,我添加的print('the salary information')
:
super(AbstractClass,self).__init__() # which does not work
您需要将 CURRENT class 传递给 super
,而不是 parent。所以:
super(Employee,self).__init__()
Python 会找出调用哪个 parent class。
当你这样做时,它不会起作用,因为 AbstractClass.__init__
需要一个你没有提供的额外参数。
跟进
已正确指出这就足够了:
super().__init__(0)