[英]A Python Inheritance Problem: TypeError: super() argument 1 must be type, not None
I want to save the class name and class itself into a python dict by using a decorator.我想使用装饰器将 class 名称和 class 本身保存到 python 字典中。
from functools import wraps
models = {} # python dict which save class name and class
def register_model(name):
def register(func):
@wraps(func)
def inner(name):
models[name] = func
return inner(name)
return register
# `A` is a class that I want to save into the dict.
@register_model('1244')
class A(object):
a = 1
def __init__(self):
super(A, self).__init__()
# But when call it below:
print(models['1244']().a)
I get an error:我收到一个错误:
Traceback (most recent call last):
File "/Data/Usr/t.py", line 50, in <module>
print(models['1244']().a)
File "/Data/Usr/t.py", line 36, in __init__
super(A, self).__init__()
TypeError: super() argument 1 must be type, not None
I solve this error by changing super(A, self).__init__()
to super().__init__()
我通过将
super(A, self).__init__()
更改为super().__init__()
__() 来解决此错误
I want to know why augment 1 is None and what cause it.我想知道为什么 augment 1 是 None 以及是什么原因造成的。
The decorator doesn't return anything, and whatever it returns will be assigned to the name A
(the class definition).装饰器不返回任何东西,它返回的任何东西都将分配给名称
A
(class 定义)。 You're making the class accessible solely through models['1244']
, A()
as such doesn't work (because A
is None
).您正在使 class 只能通过
models['1244']
访问,因此A()
不起作用(因为A
是None
)。 This is what's happening when you do super(A, ...)
.这就是你做
super(A, ...)
时发生的事情。
A
to super
, just super().__init__()
will do just fine.A
传递给super
,只需super().__init__()
就可以了。 This would resolve this particular problem. In fact, your decorator is overly complicated.实际上,您的装饰器过于复杂。
inner
is completely superfluous. inner
完全是多余的。 Change it to this to solve both issues:将其更改为此以解决这两个问题:
def register_model(name):
def register(cls):
models[name] = cls
return cls
return register
Now it just registers the class in models
and otherwise lets it pass through unchanged.现在它只是在
models
中注册 class,否则让它通过不变。
Your decorator returns None
, so A
in the original scope ends up being None
, and super(A, self)
with A = None
is an invalid call.您的装饰器返回
None
,因此原始 scope 中的A
最终为None
,而带有A = None
的super(A, self)
是无效调用。 The simple fix is to return func
from the decorator.简单的解决方法是从装饰器
return func
。
Simplifying your code and getting rid of outdated idioms such as inheriting from object
and super(..., ...)
, things work fine:简化您的代码并摆脱过时的习惯用法,例如从
object
和super(..., ...)
继承,一切正常:
models = {}
def register_model(name):
def register(cls):
models[name] = cls
return cls
return register
@register_model('1244')
class A:
a = 1
def __init__(self):
super().__init__()
print("Hi!")
print(models['1244']().a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.