在基类函数装饰器中访问派生类属性

时间:2016-11-14 23:33:33

标签: python introspection python-decorators

我想做类似的事情:

class A(Resource):
  @dec(from_file=A.docpath)
  def get(self):
     pass

class B(A):
  docpath = './docs/doc_for_get_b.json'

class C(A):
  docpath = './docs/doc_for_get_c.json'

def dec(*args, **kwargs):
    def inner(f):
       docpath = kwargs.get('from_file')
       f.__kwargs__ = open(path, 'r').read()
       return f
    return inner

将调用的函数为B.getC.get,而不是A.get

如何访问docpathclass B中定义的自定义属性class C,并将其传递给getclass A函数的装饰器?< / p>

当前解决方案:将装饰器放在每个派生类上......

class A(Resource):
  def _get(self):
     pass

class B(A):
  @dec(from_file='./docs/doc_for_get_b.json')
  def get(self):
     return self._get()

class C(A)
  @dec(from_file='./docs/doc_for_get_c.json')
  def get(self):
     return self._get()

这可行,但与前一代码中的类的单行声明相比,它非常难看。

1 个答案:

答案 0 :(得分:1)

要在装饰器内访问类的属性很简单:

def decorator(function):

    def inner(self):
        self_type = type(self)
        # self_type is now the class of the instance of the method that this
        # decorator is wrapping
        print('The class attribute docpath is %r' % self_type.docpath)

        # need to pass self through because at the point function is
        # decorated it has not been bound to an instance, and so it is just a
        # normal function which takes self as the first argument.
        function(self)

    return inner


class A:
    docpath = "A's docpath"

    @decorator
    def a_method(self):
        print('a_method')


class B(A):
    docpath = "B's docpath"

a = A()
a.a_method()

b = B()
b.a_method()

一般情况下,我发现使用多层装饰器,即装饰工厂功能,可以创建装饰,例如你使用的装饰器,如:

def decorator_factory(**kwargs):

    def decorator_function(function):

        def wrapper(self):

            print('Wrapping function %s with kwargs %s' % (function.__name__, kwargs))
            function(self)

        return wrapper

    return decorator_function


class A:

    @decorator_factory(a=2, b=3)
    def do_something(self):
        print('do_something')

a = A()
a.do_something()

在阅读代码时难以理解并且不易理解,因此我倾向于使用类属性和通用超类方法来支持许多装饰器。

因此,在您的情况下,不要将文件路径作为参数传递给装饰器工厂,而是将其设置为派生类的类属性,然后在超类中编写一个读取来自实例类的class属性。