Python装饰器有哪些常见用途? [英] What are some common uses for Python decorators?

查看:107
本文介绍了Python装饰器有哪些常见用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我想将自己视为一个相当称职的Python编码人员,但我从来没能用过的语言的一个方面就是装饰器。

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.

我知道它们是什么(表面上),我已经阅读了有关堆栈溢出的教程,示例和问题,并且我了解语法,可以编写自己的语法,偶尔使用@classmethod和@staticmethod,但是我从来没有想到使用装饰器来用我自己的Python代码解决问题。我从来没有遇到过这样的问题,我想:嗯...这看起来像是装饰工!

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):
    ...

这篇关于Python装饰器有哪些常见用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆