Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.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 3.x_Decorator_Static Methods_Class Method - Fatal编程技术网

如何用Python中的类实现装饰器?

如何用Python中的类实现装饰器?,python,python-3.x,decorator,static-methods,class-method,Python,Python 3.x,Decorator,Static Methods,Class Method,上述语法可以翻译为: 显示=装饰器功能(显示) 同样的事情也可以通过一个类来完成 def decorator_function(original_function): def wrapper_function(): print('wrapper_function executed before {}'.format(original_function.__name__)) return original_function() return wrap

上述语法可以翻译为: 显示=装饰器功能(显示)

同样的事情也可以通过一个类来完成

def decorator_function(original_function):
    def wrapper_function():
        print('wrapper_function executed before {}'.format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function   
def display():
    print('display function ran...')
我可以理解这个实现。但我不明白语法是如何在后台翻译的,就像我在decorator_函数中提到的那样。 我也无法理解decorator是如何用@classmethod和@staticmethod实现的。
有人能举个例子吗?

当源代码中使用装饰器时,python(不/不必)会关心它是如何实现的。您可以自己编写:
display=decorator\u class(display)
以获得相同的结果。
@decorator\u class
语法的工作方式与
@decorator\u函数
的工作方式完全相同:它调用decorator并将结果重新分配给
def
语句中的名称。
class decorator_class(object):

    def __init__(self, original_function):
        self.original_function = original_function

    def __call__(self):
        print('call method before {}'.format(self.original_function.__name__))
        self.original_function()

@decorator_class
def display():
    print('display function ran...')