class Student(object):
def __init__(self,name):
self.name=name
def __call__(self,age,sex):
print("age is :{age},sex is :{sex}".format(age=age,sex=sex))
s=Student("Jack")
s(20,"man")
执行结果如下:
age is :20,sex is :man
__call__魔法函数的典型应用:装饰器类
如下代码:decorator(name=“func_decorator”)本身是一个对象,乍一看,这里好像使用了对象来装饰一个函数,这显然是不合理的,因此,这里就是使用了__call__魔法函数,即虽然decorator(name=“func_decorator”)是一个对象了,但是继续当函数调用,此时走到的是类中的__call__魔法函数方法中
class decorator(object):
def __init__(self, name="hello world"):
self.name = name
def __call__(self, func):
def wrapper(*args, **kwargs):
print("before func {func}()...".format(func=func.__name__))
print("name= {name}".format(name=self.name))
result = func(*args, **kwargs)
print("after func {func}()...".format(func=func.__name__))
return result
return wrapper
@decorator(name="func_decorator")
def func(a, b=10):
print("in func func3()...")
print("a={a}, b= {b}".format(a=a, b=b))
func(10,b=100)
执行结果如下:
before func func()...
name= func_decorator
in func func3()...
a=10, b= 100
after func func()...