Can a decorator of an instance method access the class?

后端 未结 13 969
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 12:33

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.

13条回答
  •  广开言路
    2020-11-27 13:07

    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.

提交回复
热议问题