设为首页 收藏本站
查看: 1387|回复: 0

[经验分享] 【转】 python中的 @ 修饰符

[复制链接]

尚未签到

发表于 2017-4-24 10:26:49 | 显示全部楼层 |阅读模式
  原文地址:http://blog.csdn.net/lainegates/article/details/8166764
今天看到python中的一个修饰符'@',不了解它的使用,查看了下官方文档,有了一点了解。
原文 PEP-318 网址:http://www.python.org/dev/peps/pep-0318/
不得不佩服老外,治学很严谨,在python网站相关网页上把为什么使用decorator(主要为了简便一些代码),以及使用什么字符,甚至语法怎么设计写了个详详细细,好长的一篇啊。
这是查看的其中一篇,我翻译关键部分的一些内容,又摘取一些有用的,有空再翻译。
 
 
[python] view plaincopy 



  • @dec2  
  • @dec1  
  • def func(arg1, arg2, ...):  
  •     pass  

  
This is equivalent to(等价于):
 
 
[python] view plaincopy 



  • def func(arg1, arg2, ...):  
  •     pass  
  • 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 plaincopy 



  • def onexit(f):  
  •     import atexit  
  •     atexit.register(f)  
  •     return f  
  •  
  • @onexit  
  • def func():  
  •     ...  


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 plaincopy 



  • def singleton(cls):  
  •     instances = {}  
  •     def getinstance():  
  •         if cls not in instances:  
  •             instances[cls] = cls()  
  •         return instances[cls]  
  •     return getinstance  
  •  
  • @singleton  
  • class MyClass:  
  •     ...  


余下基本可以参照着读懂了,以后再翻译。
3.Add attributes to a function. (Based on an example posted by Anders Munch on python-dev.)
[python] view plaincopy 



  • def attrs(**kwds):  
  •     def decorate(f):  
  •         for k in kwds:  
  •             setattr(f, k, kwds[k])  
  •         return f  
  •     return decorate  
  •  
  • @attrs(versionadded="2.2",  
  •        author="Guido van Rossum")  
  • def mymethod(f):  
  •     ...  


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 plaincopy 



  • def accepts(*types):  
  •     def check_accepts(f):  
  •         assert len(types) == f.func_code.co_argcount  
  •         def new_f(*args, **kwds):  
  •             for (a, t) in zip(args, types):  
  •                 assert isinstance(a, t), \  
  •                        "arg %r does not match %s" % (a,t)  
  •             return f(*args, **kwds)  
  •         new_f.func_name = f.func_name  
  •         return new_f  
  •     return check_accepts  
  •   
  • def returns(rtype):  
  •     def check_returns(f):  
  •         def new_f(*args, **kwds):  
  •             result = f(*args, **kwds)  
  •             assert isinstance(result, rtype), \  
  •                    "return value %r does not match %s" % (result,rtype)  
  •             return result  
  •         new_f.func_name = f.func_name  
  •         return new_f  
  •     return check_returns  
  •  
  • @accepts(int, (int,float))  
  • @returns((int,float))  
  • def func(arg1, arg2):  
  •     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 plaincopy 



  • def provides(*interfaces):  
  •      """ 
  •      An actual, working, implementation of provides for 
  •      the current implementation of PyProtocols.  Not 
  •      particularly important for the PEP text. 
  •      """  
  •      def provides(typ):  
  •          declareImplementation(typ, instancesProvide=interfaces)  
  •          return typ  
  •      return provides  
  •   
  • class IBar(Interface):  
  •      """Declare something about IBar here"""  
  •  
  • @provides(IBar)  
  • class Foo(object):  
  •         """Implement something here..."""  

Of course, all these examples are possible today, though without syntactic support.


df PSdf 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-368520-1-1.html 上篇帖子: Python 学习入门(30)—— 多态 下篇帖子: python reids client
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表