这个python装饰器如何工作? [英] How does this python decorator work?

查看:48
本文介绍了这个python装饰器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑/澄清以使我的问题特定于我的查询
*我可以看到装饰器静态日志函数的调用方式,但我看不到 _ 被调用,以及它的结果是log的结果。我可以看到输入/输入内容的工作原理*

Edit/Clarification to make my question specific to my query: *I can see how the decorator static log function is called but I don't see how _ is called and how the result of it is the result of log. I cam see how the entry/enter stuff works*

class logger:
    @staticmethod
    def log(func):
        def ___(*args, **kwargs):
            try:
                print "Entering: [%s] with parameters %s" % (func.__name__, args)
                try:
                    return func(*args, **kwargs)
                except Exception, e:
                    print 'Exception in %s : %s' % (func.__name__, e)
            finally:
                print "Exiting: [%s]" % func.__name__
        return ___


class x:
      @logger.log
      def first_x_method(self):
          print 'doing first_x_method stuff...'

x().first_x_method()

提供以下输出:

Entering: [first_x_method] with parameters (<__main__.x instance at 0x0000000001F45648>,)
doing first_x_method stuff...
Exiting: [first_x_method]

我可以看到logger是一个带有用于装饰的静态方法的类( @ logger.log )first_x_method。

I can see that logger is a class with a static method that is used to decorate (@logger.log) first_x_method.

但是我不明白为什么调用 ___ 子方法(可以是任何名称)。

However I don't understand why the ___ sub method (and it can be any name) is called.

推荐答案

关于装饰器的基本事实是

The fundamental fact about decorators is that

@decorator
def func(): ...    

是完全等于

def func(): ...
func=decorator(func)

所以,

@logger.log
def first_x_method(self): ...

def first_x_method(self): ...
first_x_method=logger.log(first_x_method)

,因此 logger.log 静态方法使用参数 func = first_x_method

and so the logger.log static method is called with argument func = first_x_method.

在对 logger.log(first_x_method)的调用中,则定义并返回子方法 __

Inside the call to logger.log(first_x_method), the sub method __ is defined and returned.

first_x_method = logger.log(first_x_method)从而将 first_x_method 设置为引用子方法 __

first_x_method=logger.log(first_x_method) thus sets first_x_method to refer to the sub method __.

first_x_method()中的括号告诉Python调用方法 first_x_method

The parenthesis in first_x_method() tells Python to call the method first_x_method.

因此 x()。first_x_method()首先实例化类x的实例,然后调用方法 first_x_method (使用x()作为第一个参数)。

So x().first_x_method() first instantiates an instance of the class x, and then calls the method first_x_method (with x() supplied as the first argument).

由于 first_x_method 是指 __ ,它是被调用的 __

Since first_x_method refers to __, it is __ that gets called.

这篇关于这个python装饰器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆