Python装饰程序范围问题
我有一个静态类,它有一个方法hello。我想在hello之前运行decorator方法栏。但是,使用下面的代码,我总是会得到一个“name‘bar’is not defined”错误。有人知道发生了什么事吗?谢谢Python装饰程序范围问题,python,class,static,decorator,Python,Class,Static,Decorator,我有一个静态类,它有一个方法hello。我想在hello之前运行decorator方法栏。但是,使用下面的代码,我总是会得到一个“name‘bar’is not defined”错误。有人知道发生了什么事吗?谢谢 class foo(): @staticmethod @bar def hello(): print "hello" def bar(fn): def wrapped(): print "bar"
class foo():
@staticmethod
@bar
def hello():
print "hello"
def bar(fn):
def wrapped():
print "bar"
return fn()
return wrapped
foo.hello()
因为它还没有定义。此外,那个装饰师根本不应该是一种方法
def bar(fn):
# ...
class foo(object):
@staticmethod
@bar
def hello():
# ...
# ...
另外,不要使用静态方法,除非你真的知道自己在做什么。将其改为自由函数。,因为它尚未定义。此外,那个装饰师根本不应该是一种方法
def bar(fn):
# ...
class foo(object):
@staticmethod
@bar
def hello():
# ...
# ...
另外,不要使用静态方法,除非你真的知道自己在做什么。将其改为免费函数。您只需将代码更改为:
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)
因此,您试图在定义函数之前调用它。您只需将代码更改为:
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)
因此,在定义函数之前,您试图调用它。为什么“不使用静态方法”?@agf:因为它们基本上是无用的。类方法在某些情况下很有用,但我想不出静态方法的用例。这不是Java。如果一个模块中有多个类,只是为了让事情有条理。为什么“不使用静态方法”?@agf:因为它们基本上是无用的。类方法在某些情况下很有用,但我想不出静态方法的用例。这不是Java。如果一个模块中有多个类,只是为了使事情有条理。