【发布时间】:2023-04-04 13:42:02
【问题描述】:
我试图理解为什么我的类上的装饰器在尝试从另一个脚本导入类时会以这种方式修改类,使其看起来是“NoneType”。
在 my_class.py 我有:
my_dict = dict()
def register(cls):
name = cls.__name__
my_dict[name] = cls
@register # will be commented
class MyClass:
def my_method(self):
print("running class method")
print("my_dict: ", my_dict)
在另一个模块中 my_main.py 我导入了类似的类
from my_class import MyClass
print(type(MyClass))
print(MyClass.my_method)
如果我使用$ python3 my_main.py 运行它,我会得到以下输出:
my_dict: {'MyClass': <class 'my_class.MyClass'>}
<class 'NoneType'>
Traceback (most recent call last):
File "my_main.py", line 4, in <module>
print(MyClass.my_method)
AttributeError: 'NoneType' object has no attribute 'my_method'
通过注释my_class.py 中的@register 行,my_main.py 运行时不会出现错误并输出:
my_dict: {}
<class 'type'>
<function MyClass.my_method at 0x7ff06f254f28>
..但显然 my_dict 不再填充。有没有办法用给定的装饰器注册my_class 并在将它导入另一个脚本后访问类的属性?
【问题讨论】:
-
你的装饰器不会返回你的类(但 None 隐含)。在您的注册功能中添加
return cls -
哦,当然……现在说得通了——非常感谢!
标签: python class import decorator python-decorators