Answer the question
In order to leave comments, you need to log in
Pass the class itself to the class method decorator
Here is a simple decorator:
def deco(clazz):
def dec(fn):
print clazz,fn
return fn
return dec
class Foo(object):
@deco(Foo)
def Bar():
print "bar"
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
class Foo(object):
File "<pyshell#12>", line 2, in Foo
@deco(Foo)
NameError: name 'Foo' is not defined
Answer the question
In order to leave comments, you need to log in
Because at the time of the execution of the class body, it has not yet been formed.
You can for example like this:
import traceback
def deco():
clazz = traceback.extract_stack()[1][2]
def dec(fn):
print clazz,fn
return fn
return dec
class Foo(object):
@deco()
def Bar():
print "bar"
Method level decorator - solves the issues of the method itself. And it is not correct to try to extend it to the class level. Understand that a method can be declared anywhere and assigned to any class in any other method. What should the decorator return in this case? Such a python. It is necessary to try to reformulate the problem, perhaps the solution is not in the decorators at all?
It looks like what implements the answer to the question posed is this example:
wiki.python.org/moin/PythonDecoratorLibrary#CA-1f74040af898602b483f2d7691d29b4a5644cce2_1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question