我正在尝试以这种方式将 super() 用于简单的类层次结构:
class Employee(object):
def __init__(self, name):
self.name = name
class FullTime(Employee):
def __init__(self, name, satOff, freeDays=[], alDays=[], programDays=[]):
global satsOffDict
global dayDict
super(Employee, self).__init__(name)
但是,我收到了这个错误:
TypeError: object.__init__() takes no parameters
我读到您需要创建父对象类型对象(新样式类)才能使 super 工作。如果我将 class Employee(object) 更改为 class Employee(),我会收到此错误:
TypeError: must be type, not classobj
这是怎么回事?
最佳答案
您在 super()
中使用 current 类:
super(FullTime, self).__init__(name)
super()
查找与第一个参数相关的请求方法;您从 Employee
开始搜索,寻找父类; object.__init__()
是在这种情况下匹配的下一个父方法。
你需要使用当前类,因为Python需要在Method Resolution Order中搜索基类;该顺序取决于您当前的类是如何从其基类派生的(尤其是在存在多重继承或基类最终被多次引用的情况下)。
在 Python 3.x 上,您可以使用不带任何参数的 super()
,并且 compiler will add an extra hint to your method以便它可以确定从哪个正确的类开始。
关于python - 在类中使用 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242033/