【发布时间】:2021-08-01 04:57:36
【问题描述】:
我有以下代码段,其输出如下所示
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
【问题讨论】:
-
顺便说一句,值得注意的是,在这样的子类中更改
__init__的签名违反了 Liskov 替换原则,因此可能不可取。很难就修复提出建议,因为尚不清楚您的n属性的目的是什么。 en.wikipedia.org/wiki/Liskov_substitution_principle
标签: python python-3.x abstract-class abc