只执行一次的装饰器


最近在看 参考手册,写的真心好,不过有些地方不够详细 p83 


event_handler={}
def eventhandler(event):
    def register(f):
        print(event)
        event_handler[event] = f
        return f
    return register

@eventhandler("button")
def handle_button(msg):
    print('this is %s button handle!~'%(msg))


handle_button('good')
handle_button('good')
handle_button('fuck')
print(event_handler)

猜猜结果是什么:


button
this is good button handle!~
this is good button handle!~
this is good button handle!~
this is fuck button handle!~
{'button': <function handle_button at 0x01705198>}


是不是出乎意料啊 


原来是这样的

# temp = eventhandler("button")
# handle_button = temp(handle_button) = register(handle_button) = handle_button

第一次执行的会变成这样,以后就是自身了, 发现他的伟大用处了吗,尽量想把,哈哈


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值