【转】 python中的 @ 修饰符

原文地址:http://blog.csdn.net/lainegates/article/details/8166764

今天看到python中的一个修饰符'@',不了解它的使用,查看了下官方文档,有了一点了解。

原文 PEP-318 网址:http://www.python.org/dev/peps/pep-0318/

不得不佩服老外,治学很严谨,在python网站相关网页上把为什么使用decorator(主要为了简便一些代码),以及使用什么字符,甚至语法怎么设计写了个详详细细,好长的一篇啊。

这是查看的其中一篇,我翻译关键部分的一些内容,又摘取一些有用的,有空再翻译。

 

 

[python]  view plain copy
 
  1. @dec2  
  2. @dec1  
  3. def func(arg1, arg2, ...):  
  4.     pass  


This is equivalent to(等价于):

 

 

[python]  view plain copy
 
  1. def func(arg1, arg2, ...):  
  2.     pass  
  3. func = dec2(dec1(func))  


使用示例:

 

Much of the discussion on comp.lang.python and the python-dev mailing list focuses on the use of decorators as a cleaner way to use the staticmethod() and classmethod() builtins. This capability is much more powerful than that. This section presents some examples of use.

comp.lang.python 和 python-dev的大部分讨论集中在更简捷地使用内置修饰符staticmethod() 和 classmethod() 上。但修饰符的功能远比这强大。下面会对它的使用进行一些讲解:

 

1.Define a function to be executed at exit. Note that the function isn't actually "wrapped" in the usual sense.

1.定义一个执行即退出的函数。注意,这个函数并不像通常情况那样,被真正包裹。
[python]  view plain copy
 
  1. def onexit(f):  
  2.     import atexit  
  3.     atexit.register(f)  
  4.     return f  
  5.  
  6. @onexit  
  7. def func():  
  8.     ...  

Note that this example is probably not suitable for real usage, but is for example purposes only.
注意,这个示例可能并不能准确表达在实际中的使用,它只是做一个示例。

2. Define a class with a singleton instance. Note that once the class disappears enterprising programmers would have to be more creative to create more instances. (From Shane Hathaway onpython-dev.)

2.定义一个只能产生一个实例的类(有实例后,这个类不能再产生新的实例)。注意,一旦这个类失效了(估计意思是保存在下文的singleton中字典中的相应键失效),就会促使程序员让这个类产生更多的实例。(来自于 python-dev的Shane Hathaway
[python]  view plain copy
 
  1. def singleton(cls):  
  2.     instances = {}  
  3.     def getinstance():  
  4.         if cls not in instances:  
  5.             instances[cls] = cls()  
  6.         return instances[cls]  
  7.     return getinstance  
  8.  
  9. @singleton  
  10. class MyClass:  
  11.     ...  

余下基本可以参照着读懂了,以后再翻译。
3.Add attributes to a function. (Based on an example posted by Anders Munch on  python-dev .)
[python]  view plain copy
 
  1. def attrs(**kwds):  
  2.     def decorate(f):  
  3.         for k in kwds:  
  4.             setattr(f, k, kwds[k])  
  5.         return f  
  6.     return decorate  
  7.  
  8. @attrs(versionadded="2.2",  
  9.        author="Guido van Rossum")  
  10. def mymethod(f):  
  11.     ...  

4. Enforce function argument and return types. Note that this copies the func_name attribute from the old to the new function. func_name was made writable in Python 2.4a3:
[python]  view plain copy
 
  1. def accepts(*types):  
  2.     def check_accepts(f):  
  3.         assert len(types) == f.func_code.co_argcount  
  4.         def new_f(*args, **kwds):  
  5.             for (a, t) in zip(args, types):  
  6.                 assert isinstance(a, t), \  
  7.                        "arg %r does not match %s" % (a,t)  
  8.             return f(*args, **kwds)  
  9.         new_f.func_name = f.func_name  
  10.         return new_f  
  11.     return check_accepts  
  12.   
  13. def returns(rtype):  
  14.     def check_returns(f):  
  15.         def new_f(*args, **kwds):  
  16.             result = f(*args, **kwds)  
  17.             assert isinstance(result, rtype), \  
  18.                    "return value %r does not match %s" % (result,rtype)  
  19.             return result  
  20.         new_f.func_name = f.func_name  
  21.         return new_f  
  22.     return check_returns  
  23.  
  24. @accepts(int, (int,float))  
  25. @returns((int,float))  
  26. def func(arg1, arg2):  
  27.     return arg1 * arg2  

5. Declare that a class implements a particular (set of) interface(s). This is from a posting by Bob Ippolito on  python-dev  based on experience with  PyProtocols   [27] .
[python]  view plain copy
 
  1. def provides(*interfaces):  
  2.      """ 
  3.      An actual, working, implementation of provides for 
  4.      the current implementation of PyProtocols.  Not 
  5.      particularly important for the PEP text. 
  6.      """  
  7.      def provides(typ):  
  8.          declareImplementation(typ, instancesProvide=interfaces)  
  9.          return typ  
  10.      return provides  
  11.   
  12. class IBar(Interface):  
  13.      """Declare something about IBar here"""  
  14.  
  15. @provides(IBar)  
  16. class Foo(object):  
  17.         """Implement something here..."""  
Of course, all these examples are possible today, though without syntactic support.

df PSdf 

猜你喜欢

转载自luchuan.iteye.com/blog/2251004