I have a static class that has a method hello. I want to run the decorator method bar before hello. However, using the following code I always get a "name 'bar' is not defined" error. Does anyone know what's going on? Thanks!
class foo():
@staticmethod
@bar
def hello():
开发者_StackOverflow print "hello"
def bar(fn):
def wrapped():
print "bar"
return fn()
return wrapped
foo.hello()
Because it's not defined yet. Besides, that decorator shouldn't be a method at all.
def bar(fn):
# ...
class foo(object):
@staticmethod
@bar
def hello():
# ...
# ...
Also, don't use static methods, unless you really know what you're doing. Make it a free function instead.
You can just change your code to:
def bar(fn):
def wrapped():
print "bar"
return fn()
return wrapped
class foo():
@staticmethod
@bar
def hello():
print "hello"
foo.hello()
This happens because you have to define a function before you call it. This is a problem because this:
@bar
def hello():
print "hello"
is equivalent to:
def hello():
print "hello"
hello = bar(hello)
So you were trying to call the function before you defined it.
精彩评论