Python 使用装饰器链在程序出口处注册类方法
我有一个类,它的一个属性是我想在程序退出时运行的类方法。这个直接的想法是:Python 使用装饰器链在程序出口处注册类方法,python,python-decorators,class-method,atexit,Python,Python Decorators,Class Method,Atexit,我有一个类,它的一个属性是我想在程序退出时运行的类方法。这个直接的想法是: import atexit class Foo: @atexit.register @classmethod def foo(cls): pass 引发以下异常: Traceback (most recent call last): File "test.py", line 3, in <module> class Foo: File "test.p
import atexit
class Foo:
@atexit.register
@classmethod
def foo(cls):
pass
引发以下异常:
Traceback (most recent call last):
File "test.py", line 3, in <module>
class Foo:
File "test.py", line 5, in Foo
@classmethod
TypeError: the first argument must be callable
Error in atexit._run_exitfuncs:
TypeError: foo() missing 1 required positional argument: 'cls'
引发以下异常:
Traceback (most recent call last):
File "test.py", line 3, in <module>
class Foo:
File "test.py", line 5, in Foo
@classmethod
TypeError: the first argument must be callable
Error in atexit._run_exitfuncs:
TypeError: foo() missing 1 required positional argument: 'cls'
我对装饰师的概念很陌生
- 有没有简单的方法可以在仍然使用decorators链的情况下修复此代码
- 如果不是,您会推荐什么替代解决方案
def mydeco(func):
print(repr(func))
return func
class Foo:
@mydeco
@classmethod
def foo(cls):
pass
print(repr(Foo.foo))
如果你运行这个,你会看到
<classmethod object at 0x6ffffd1dc18>
<bound method Foo.foo of <class '__main__.Foo'>>
非常感谢。解释得很好。classmethod对象对我来说有点像黑魔法,但至少我最终理解了“参数不可调用”异常。我不知道装饰师可以返回对象。