本文介绍了语句装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些代码如下所示:

  from third_party_library import foo 

for n (3):
试试:
foo(args)
break
除了:
print重试%i / 3%n

我想使用一个装饰器,让我们的代码变得更简洁,如下所示:

  from third_party_library import foo 

@retry(3)
foo(args)

这给出了语法错误。我是否错过了一些东西,或者python只是不允许装饰器在语句上?

解决方案

装饰器只能应用于函数和类定义,如:

  @decorator 
def func():
。 ..

@decorator
class MyClass(object):
...

您不能在语言的任何其他地方使用它们。






要做你想做的事,你可以做一个正常的 retry 函数并传递 foo args 作为参数。这个实现看起来像这样:
$ b $ pre $ def $ re $(times,func,* args,** kwargs)
在xrange(times)中为n:
try:
func(* args,** kwargs)
break
除了Exception:#尝试捕捉更具体的
打印重试%i /%i%(n,次)


We have some code that looks like this:

from third_party_library import foo

for n in range(3):
    try:
        foo(args)
        break
    except:
        print "Retry %i / 3" % n

I would like to use a decorator, allowing our code to be more consise, looking like this:

from third_party_library import foo

@retry(3)
foo(args)

This gives a syntax error. Am I missing something, or does python just not allow decorators on statements?

解决方案

Decorators can only be applied to function and class definitions such as:

@decorator
def func():
    ...

@decorator
class MyClass(object):
    ...

You cannot use them anywhere else in the language.


To do what you want, you could make a normal retry function and pass foo and args as arguments. The implementation would look something like this:

def retry(times, func, *args, **kwargs):
    for n in xrange(times):
        try:
            func(*args, **kwargs)
            break
        except Exception:  # Try to catch something more specific
            print "Retry %i / %i" % (n, times)

这篇关于语句装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:39