#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
#装饰器01
#特点是: Allows functions and methods to be encapsulated (receiving a function and returning an enhanced version of a function)
#语法: The original scene can define the method as a class method or a static method at the definition header, before the adorner is used, the syntax is as follows:
Class Whatfort (object):
def it (CLS):
print ' Work with%s: '%cls
It=classmethod (IT)
def uncommon (self):
print ' I could be a global function '
Unicode=staticmethod (Unicode)
When there are multiple transformations in the #当方法很大或者在该方法, it becomes difficult to use
#使用装饰器之后
Class A (object):
@classmethod
def it (CLS):
print ' Work with%s: '%cls
@staticmethod
def Unicode ():
print ' I could be a global function '
A=a ()
A.It () #work with <class ' __main__. A ';:
A.unicode () #i could be a global function
#如何编写装饰器呢?
#通用方法
def mydecorator (func):
def _mydecorate (*args,**kwargs):
#在调用实际函数之前做些填充工作
Res=func (*args,**kwargs)
#在调用完之后进行某些填充工作
return res
#返回子函数
Return _mydecorate
It is a good practice to #为子函数应用一保比如 explicit names such as _mydecorate, rather than generic names like those in front of them, because it is easier to have a clear name backtracking when an error occurs-knowing that the specified adorner is being processed
#当装饰器需要参数时, you must use a second-level package
def my (AR1,AR2):
def _my (func):
def __my (*a,**k):
#在调用实际函数之前做些填充工作
Res=func (*a,**k)
#在调用完之后进行某些填充工作
return res
#返回子函数
Return __my
Return _my
#因为装饰器在模块第一次被读取时由解释程序装入, so their use must be limited by the overall application of the wrapper, and if the adorner is bound to the class of the method or the enhanced function signature, it should be refactored into a regular callable object
#注意: adorners should focus on the parameters that are received and returned by the encapsulated function or method and, if necessary, limit their introspection to work as much as possible
#常见的装饰器模式括号 (parameter check, cache, proxy, context provider)
#更多 (provided by netizens:) http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
#http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
#http://blog.csdn.net/hackerain/article/details/7842159