TypeError: super() argument 1 must be type, not classobj
这个错误通常出现在 Python 2 中,它和 Python 2 里经典类(classobj)与新式类(type)的区别有关。
在 Python 2 里,存在经典类和新式类两种不同的类定义方式:
经典类:定义类时不继承自 object 类,例如 class ClassicClass:。经典类的类型是 classobj
新式类:定义类时继承自 object 类,例如 class NewStyleClass(object):。新式类的类型是 type
super() 函数在 Python 2 中只能用于新式类,当你将经典类的类名作为 super() 的第一个参数时,就会抛出 TypeError: super() argument 1 must be type, not classobj 错误,因为 super() 要求第一个参数必须是新式类(type 类型)。
示例代码及错误复现
# 定义一个经典类
class ParentClass:
def __init__(self):
print("ParentClass init")
class ChildClass(ParentClass):
def __init__(self):
# 这里会报错,因为 ParentClass 是经典类
super(ChildClass, self).__init__()
print("ChildClass init")
child = ChildClass()
上述代码中,ParentClass 是经典类,当在 ChildClass 中使用 super() 函数时,就会引发错误
要解决这个问题,需要将经典类转换为新式类,也就是让类继承自 object 类
# 定义一个新式类
class ParentClass(object):
def __init__(self):
print("ParentClass init")
class ChildClass(ParentClass):
def __init__(self):
# 现在可以正常使用 super() 了
super(ChildClass, self).__init__()
print("ChildClass init")
child = ChildClass()
在修改后的代码中,ParentClass 继承自 object 类,成为了新式类,此时在 ChildClass 中使用 super() 函数就不会再报错
在 Python 3 中,所有的类默认都是新式类,不存在经典类和新式类的区别,并且 super() 函数可以更简洁地使用,不需要传递参数。例如:
class ParentClass:
def __init__(self):
print("ParentClass init")
class ChildClass(ParentClass):
def __init__(self):
super().__init__()
print("ChildClass init")
child = ChildClass()
在 Python 3 里,这样的代码可以正常运行,不会出现类似的错误。
总结
在 Python 2 中遇到 TypeError: super() argument 1 must be type, not classobj 错误时,将相关类转换为新式类即可解决问题
在 Python 3 中则无需担心这个问题