`

【转】 python中的 @ 修饰符

阅读更多

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

 

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

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

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

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

 

 

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


This is equivalent to(等价于):

 

 

[python] view plaincopy
 
  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 plaincopy
 
  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 plaincopy
 
  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 plaincopy
 
  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 plaincopy
 
  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 plaincopy
 
  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 

 

分享到:
评论

相关推荐

    python函数修饰符@的使用方法解析

    主要介绍了python函数修饰符@的使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Python-pythongoto函式修饰符对bytecode进行重定向Python中的goto

    python-goto-函式修饰符, 对 bytecode 进行重定向, Python 中的 goto

    05-python-修饰符的使用-operator模块-作用域-动态编译

    python学习笔记,包含修饰符的使用-operator模块-作用域-动态编译

    05-python-迭代器-生成器-with语句和上下文管理器-修饰符

    python学习笔记,包含迭代器-生成器-with语句和上下文管理器-修饰符

    kaiwenli#python_book#10.5正则修饰符1

    正则修饰符示例:\w+$ 表示匹配以一个或者多个字母结尾re.M 可以进行多行匹配,每个换行都认为是一个结尾不实用re.M修饰符,只会匹配到最后的 man。

    python正则-re的用法详解

    今天是review,所以一些基础的概念就不做介绍了,先来看正则中的修饰符以及它的功能: 修饰符 •re.I 使匹配对大小写不敏感 •re.L 做本地化识别匹配 •re.M 多行匹配,影响^和$ •re.S 使.匹配包括换行在内的所有...

    observe:@observe是Python装饰器

    @observe是Python方法的修饰符,它使Python开发人员可以收集有关修饰后的方法的所有基本指标,生成统一的日志和关于失败的易于通知的通知。 日志,指标和通知 所有日志,指标和通知均分为三类: 默认值:未引发...

    Python拾趣009 修饰器@简介和简单应用

    在写类的时候经常用到@staticmethod或@classmethod修饰符,这样就可以不需要实例化,直接类名.方法名()来调用。 所以修饰器用到好多地方的。 例子 PyQt AND OpenCV By LiNYoUBiAo 2020/4/19 19:49 from functools...

    python实现装饰器、描述符

    本人python理论知识远达不到传授级别,写文章主要目的是自我总结,并不能照顾所有人,请见谅,文章结尾贴有相关链接可以作为补充 全文分为三个部分装饰器理论知识、装饰器应用、装饰器延申 装饰理基础:无参装饰器...

    Python面向对象编程指南

    第1部分讲述用特殊方法实现Python风格的类,分别介绍了__init__()方法、与Python无缝集成—基本特殊方法、属性访问和特性及修饰符、抽象基类设计的一致性、可调用对象和上下文的使用、创建容器和集合、创建数值类型...

    PYTHON 面向对象编程指南

    第1部分讲述用特殊方法实现Python风格的类,分别介绍了__init__()方法、与Python无缝集成—基本特殊方法、属性访问和特性及修饰符、抽象基类设计的一致性、可调用对象和上下文的使用、创建容器和集合、创建数值类型...

    【JavaScript源代码】VUE入门学习之事件处理.docx

     系统修饰键 .exact 修饰符 鼠标按钮修饰符 .exact 修饰符 鼠标按钮修饰符 总结 1. 函数绑定 可以用v-on:click="methodName"或者快捷方式 @click="methodName"绑定事件处理函数 @click="m

    Python编码风格指南(中文版)

    2.17 函数和方法修饰符 2.18 线程 2.19 高级特性 3. Python 编码风格方面的准则 3.1 分号 3.2 每行长度 3.3 圆括号 3.4 缩进 3.5 空行 3.6 空格 3.7 Python 解释器 3.8 注释 3.9 类 3.10 字符串 3.11 TODO style ...

    Python核心编程第二版

     4.6.5 Python类型操作符和内建函数总结   4.7 类型工厂函数   4.8 标准类型的分类   4.8.1 存储模型   4.8.2 更新模型   4.8.3 访问模型   4.9 不支持的类型   4.10 练习   第5章 数字 ...

    Python中的Descriptor描述符学习教程

    简单来说,数据描述符是指实现了__get__、__set__、__del__方法的类属性,等效于定义了三个方法的接口,下面就来详细看一下Python中的Descriptor修饰符学习教程

    Head First Python(第2版) 配套源码

    如果你想知道利用上下文管理器、修饰符、推导式和生成器能够做什么,都可以在这本书中找到。本书将提供一个完整的学习体验,帮助你迅速成为一名Python程序员。为什么这本书如此与众不同?根据认知科学和学习理论的z...

    Python 程序执行时间分析器 Chronic.zip

    Python 程序执行时间分析器 Chronic ,Chronic 介于简单的定时器和分析器。通过添加修饰符或包装代码语句来获得程序执行时间。Chron...

    plover-modifiers:用于创建modifiers.json词典的脚本,以解决不支持修饰符的Plover的问题

    千篇一律的修饰符 用于创建modifiers.json词典的脚本,以方便修饰符。 用法 编辑make-modifiers.py文件,然后将所需的键添加到hotkeys变量中。 例如,将["KH-FG", "grave"],到hotkeys数组中,以创建⌘ `切换窗口的...

    Python核心编程第二版(ok)

     4.6.5 Python类型操作符和内建函数总结   4.7 类型工厂函数   4.8 标准类型的分类   4.8.1 存储模型   4.8.2 更新模型   4.8.3 访问模型   4.9 不支持的类型   4.10 练习   第5章 数字 ...

    Python基础教程第2版

    修饰符:修饰符,这是可选的,告诉编译器如何调用该方法。定义了该方法的访问类型。 返回值类型 :方法可能会返回值。returnValueType 是方法返回值的数据类型。有些方法执行所需的操作,但没有返回值。在这种情况下...

Global site tag (gtag.js) - Google Analytics