python 关于@的解释

自从开始学习python,看源码的时候经常可以看到@来修饰的方法,之前一直没搞清楚。现在汇总下自己对于@的理解:

@是python的修饰符,Decorator类类似于C的预编译宏,因此在代码函数调用之前或者执行main函数之前就已经完成了编译。

我可以创建修饰类或者是修饰方法,用来修饰方法。在写一个修饰类的时候,必须要实现它的__CALL__方法。

1.修饰类(编译过程)

class decorator(object):
    def __init__(self,f):
        print "inside decorator.__init__"
        f()
    def __call__(self):
        print "inside decorator.__call__"

@decorator
def aFunction():
    print "inside aFunction()"

print "Finished decorating aFunction()"
aFunction()
输出结果:

inside decorator.__init__
inside aFunction()
Finished decorating aFunction()
inside decorator.__call__
这个是一个修饰类,我们可以看到它的编译过程,在调用之前就已经编译完成

2.修饰方法(其中可以理解参数的传递)

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):

    print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2

    def my_decorator(func):
        # The ability to pass arguments here is a gift from closures.
        # If you are not comfortable with closures, you can assume it's ok,
        # or read: http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2

        # Don't confuse decorator arguments and function arguments!
        def wrapped(function_arg1, function_arg2) :
            print ("I am the wrapper around the decorated function.\n"
                  "I can access all the variables\n"
                  "\t- from the decorator: {0} {1}\n"
                  "\t- from the function call: {2} {3}\n"
                  "Then I can pass them to the decorated function"
                  .format(decorator_arg1, decorator_arg2,
                          function_arg1, function_arg2))
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
    print ("I am the decorated function and only knows about my arguments: {0}"
           " {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments("Rajesh", "Howard")
输出结果:

I make decorators! And I accept arguments: Leonard Sheldon
I am the decorator. Somehow you passed me arguments: Leonard Sheldon
I am the wrapper around the decorated function.
I can access all the variables
	- from the decorator: Leonard Sheldon
	- from the function call: Rajesh Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Rajesh Howard

由此2种方式应该可以完全理解了~



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值