您的位置:首页 > 编程语言 > Python开发

python 关于@的解释

2013-08-27 14:14 288 查看
自从开始学习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种方式应该可以完全理解了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: