Can a decorator of an instance method access the class?

后端 未结 13 933
没有蜡笔的小新
没有蜡笔的小新 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:01

    As Ants indicated, you can't get a reference to the class from within the class. However, if you're interested in distinguishing between different classes ( not manipulating the actual class type object), you can pass a string for each class. You can also pass whatever other parameters you like to the decorator using class-style decorators.

    class Decorator(object):
        def __init__(self,decoratee_enclosing_class):
            self.decoratee_enclosing_class = decoratee_enclosing_class
        def __call__(self,original_func):
            def new_function(*args,**kwargs):
                print 'decorating function in ',self.decoratee_enclosing_class
                original_func(*args,**kwargs)
            return new_function
    
    
    class Bar(object):
        @Decorator('Bar')
        def foo(self):
            print 'in foo'
    
    class Baz(object):
        @Decorator('Baz')
        def foo(self):
            print 'in foo'
    
    print 'before instantiating Bar()'
    b = Bar()
    print 'calling b.foo()'
    b.foo()
    

    Prints:

    before instantiating Bar()
    calling b.foo()
    decorating function in  Bar
    in foo
    

    Also, see Bruce Eckel's page on decorators.

提交回复
热议问题