python - 在类中使用 super()

标签 python oop

我正在尝试以这种方式将 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/

相关文章:

python - 添加 seaborn clustermap 以与其他图一起绘制

Python pandas 夹板字符串,添加行,每列不同

php - Magento:性能随着购物车项目数量的增加而下降

r - 如何扩展 R 包中定义的使用私有(private)函数的引用类?

php - python 后端有什么用途?

python - 同时使用 urllib2.urlopen() 进行多个请求

python - 如何使用另一个列表过滤一个列表?

ruby + OOP + 测试 : How should I test incoming command messages?

java - 如何将对象传递给稍后注入(inject)的类

regex - 在 Regex 上调用 Bool 无法按文档工作