Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用装饰器链在程序出口处注册类方法_Python_Python Decorators_Class Method_Atexit - Fatal编程技术网

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对象对我来说有点像黑魔法,但至少我最终理解了“参数不可调用”异常。我不知道装饰师可以返回对象。