python 装饰器有哪些_Python装饰器有哪些常见用途?

1586010002-jmsa.png

While I like to think of myself as a reasonably competent Python coder, one aspect of the language I've never been able to grok is decorators.

I know what they are (superficially), I've read tutorials, examples, questions on Stack Overflow, and I understand the syntax, can write my own, occasionally use @classmethod and @staticmethod, but it never occurs to me to use a decorator to solve a problem in my own Python code. I never encounter a problem where I think, "Hmm...this looks like a job for a decorator!"

So, I'm wondering if you guys might offer some examples of where you've used decorators in your own programs, and hopefully I'll have an "A-ha!" moment and get them.

解决方案

I use decorators mainly for timing purposes

def time_dec(func):

def wrapper(*arg):

t = time.clock()

res = func(*arg)

print func.func_name, time.clock()-t

return res

return wrapper

@time_dec

def myFunction(n):

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值