我试图以这种方式使用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工作.如果我将类Employee(对象)更改为类Employee(),我会收到此错误:
TypeError: must be type, not classobj
这是怎么回事?
解决方法:
您在super()中使用当前类:
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,oop
来源: https://codeday.me/bug/20190723/1510804.html