__call__
把对象当成函数后面加一对小括号执行时,会默认调用类中的__call__
对象方法
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span><span class="hljs-params">(object)</span>:</span>
<span class="hljs-comment"># per() ==> per.__call__()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self, *args, **kwargs)</span>:</span>
print(<span class="hljs-string">"----------call"</span>)
per = Person()
per()
普通装饰器
class AddXing(object):
# 传入待加功能的函数
def __init__(self, f):
self.f = f
# 传入原函数的需要参数
def __call__(self, *args, **kwargs):
#增加功能
print("**************")
res = self.f(*args, **kwargs)
return res
带参装饰器
class Count(object):
# 带参数的装饰器的参数__init__这里传递
def __init__(self, count=3):
self.count = count
# 接收待加功能的函数
def __call__(self, f):
# 传入原函数的需要参数
def inner(*args, **kwargs):
for i in range(self.count):
f(*args, **kwargs)
return inner
使用
@Count()
def func(name, age):
print("My name is %s!I am %d years old!"%(name, age))
func()
原理
@AddXing
def func(name, age):
pass
obj = AddXing(func)
func = obj
func() ==> obj() ==> obj.__call__ ==> func.__call__()
@Count(3)
def func(name, age):
pass
obj = Count(3)
inner = obj(func)
func = inner