I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.
The problem is that when the decorator is called the class doesn't exist yet. Try this:
def loud_decorator(func):
print("Now decorating %s" % func)
def decorated(*args, **kwargs):
print("Now calling %s with %s,%s" % (func, args, kwargs))
return func(*args, **kwargs)
return decorated
class Foo(object):
class __metaclass__(type):
def __new__(cls, name, bases, dict_):
print("Creating class %s%s with attributes %s" % (name, bases, dict_))
return type.__new__(cls, name, bases, dict_)
@loud_decorator
def hello(self, msg):
print("Hello %s" % msg)
Foo().hello()
This program will output:
Now decorating
Creating class Foo(,) with attributes {'__module__': '__main__', '__metaclass__': , 'hello': }
Now calling with (<__main__.Foo object at 0xb74ea1ac>, 'World'),{}
Hello World
As you see, you are going to have to figure out a different way to do what you want.