Python装饰器和__call__函数

__call__

在python中,函数其实是一个可调用的对象,实例对象可以用函数的形式表示

一个类实例可以变成一个可调用的对象,只需要实现方法__call__()

 

一、把类Myclass变成可调用的对象:

 

class Myclass(object):
    
    def __init__(self, fn):
        self.name = fn
        print fn
        
    def __call__(self, *args, **kwargs):
        print "My name is ..."
        self.name(*args, **kwargs)
        print "My friend is ..."

def getInfo(test):
    print test

cls = Myclass(getInfo)
cls('Tim')

打印:
<function myfun at 0x1005ed2a8>
<function getInfo at 0x1005e0ed8>
My name is ...
Tim
My friend is ...

 

 

二、把实例对象用类似于函数的形式表示,

 

class Test():
    def __init__(self):
        pass
    
    def __call__(self, num):
        sum = 0
        for i in range (num):
            sum += i
        return sum

t = Test()
print t(10)
打印:
45

 

 

Python装饰器:使用类来定义装饰器(Python中类实例可以当做函数一样调用)

 

class Myclass(object):
    
    def __init__(self, fn):
        self.name = fn
        print fn
        
    def __call__(self, *args, **kwargs):
        print "My name is ..."
        self.name(*args, **kwargs)
        print "My friend is ..."

def getInfo(ni):
    print ni

@Myclass
def myfun(name, gender):
    print "start..."
    print name
    print gender
    print "end..."

myfun('Bob', 'male')
打印:
<function myfun at 0x1005ee2a8>
My name is ...
start...
Bob
male
end...
My friend is ...

 小编只是举个例子。小编在实际项目中的调用场景是:

一、计算一个网页的pv流量

二、控制某些网页的访问,例如必须登录才能访问

三、在某些函数的前后打印必要的日志信息

综上:都是为了简化函数的一些流程,将统一的代码规范化,避免函数一些共性的代码重复书写

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值