Python装饰器范围问题

时间:2011-08-22 16:41:21

标签: python class static decorator

我有一个带有方法hello的静态类。我想在你好之前运行装饰器方法栏。但是,使用以下代码我总是得到一个“名称'栏'未定义”错误。有谁知道发生了什么?谢谢!

class foo():
    @staticmethod
    @bar
    def hello():
        print "hello"

    def bar(fn):
        def wrapped():
            print "bar"
            return fn()
        return wrapped

foo.hello()

2 个答案:

答案 0 :(得分:2)

因为它还没有定义。此外,装饰者根本不应该是一种方法。

def bar(fn):
    # ...

class foo(object):
    @staticmethod
    @bar
    def hello():
        # ...

# ...

另外,不要使用静态方法,除非你真的知道自己在做什么。把它变成一个免费的功能。

答案 1 :(得分:2)

您只需将代码更改为:

def bar(fn):
    def wrapped():
        print "bar"
        return fn()
    return wrapped
class foo():
    @staticmethod
    @bar
    def hello():
        print "hello"
foo.hello()

这是因为您必须在调用之前定义一个函数。这是一个问题,因为:

@bar
def hello():
    print "hello"

相当于:

def hello():
    print "hello"
hello = bar(hello)

所以你在定义之前试图调用该函数。

相关问题