添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

python 3 typeerror super(type obj) obj must be an instance or subtype of type

这个错误通常是在你试图调用父类的方法或属性时出现的。例如:

class Parent:
    def __init__(self):
        self.value = 'parent'
class Child(Parent):
    def __init__(self):
        super().__init__()
child = Child()
print(child.value)

上面的代码中,我们希望 Child 类继承父类 Parentvalue 属性,并在 Child 类的 __init__ 方法中调用父类的 __init__ 方法。但是,如果我们在调用 super() 时忘记了括号,就会出现这个错误:

class Parent:
    def __init__(self):
        self.value = 'parent'
class Child(Parent):
    def __init__(self):
        super.__init__()
child = Child()
print(child.value)

这是因为 super() 函数返回的是一个特殊的对象,用于访问父类的方法和属性。但是,如果我们忘记了括号,super 就会被当作普通的变量,而不是函数。这样,就会出现上面提到的错误:TypeError: super(type, obj): obj must be an instance or subtype of type

要解决这个问题,只需确保在调用 super() 时使用了括号即可。正确的代码如下:

class Parent:
    def __init__(self):
        self.value = 'parent'
class Child(Parent):
    def __init__(self):
        super().__init__()
child = Child()
print(child.value)

现在,这段代码应该能正常工作,并输出 parent

  •