看到网上很多用修饰器(装饰器,descriptor)学下
系统自带修饰器
@staticmethod //方法为类的静态方法
@classmethod //方法为类方法 cls ,这个比较特殊是实例和类名都可以调用,看实现
没加修饰为实例方法 self
自定义修饰器
静态方法:
相当于func = decorator(func) 返回值比较难理解!!!
一般使用,可用来过滤或是添加代码
def hello(fn):
def wrapper(args, **kwds):
print "calls %s" %(fn.name)
fn(args, **kwds)
return wrapper
@hello
def spam(a,b,c):
print a,b,c
spam(1,2,3) //此处有调用
再来看一个好玩的实例子
def hello(fn):
print "call"
def wrapper(args, **kwds):
print "calls %s" %(fn.name)
fn(args, **kwds)
return wrapper
@hello
def spam(a,b,c):
print a,b,c
spam(1,2,3)
去掉了调用,发现print "call"初调用了,慢慢理解
再来看不用函数,用类
class hello(object):
def init(self, *arg, **kwgs):
print "call init"
print arg
print kwgs
def call(self, arg, **kwgs):
print "call call"
print arg
print kwgs
def wrapped(arg, **kwgs):
print "call wrapped"
print arg
print kwgs
return wrapped
@hello(a="a", b="b")
@hello(a="a1", b="b1")
def foo(name,a):
return "Hello, {}".format(name)
print foo("Hao Chen",1)
//结果
call init
()
{'a': 'a', 'b': 'b'}
call init
()
{'a': 'a1', 'b': 'b1'}
call call
(<function foo at 0x00000000025929E8>,)
{}
call call
(<function wrapped at 0x0000000002E48438>,)
{}
('Hao Chen', 1)
{}
None
可以看出来:
init 在调用之前执行
另外 wapped只调用了一次
call 传进来了函数和相关参数
有点乱,可以参考
http://www.open-open.com/lib/view/open1395285030019.html
http://www.cnblogs.com/btchenguang/archive/2012/09/17/2689146.html
posted on
浙公网安备 33010602011771号