装饰类无法访问其属性

时间:2015-06-08 14:22:21

标签: python decorator python-decorators class-attributes

我实现了一个像魅力一样工作的装饰器,直到我将属性添加到装饰类中。当我实例化该类时,它无法访问calss属性。采取以下最小的工作示例:

from module import specialfunction

class NumericalMathFunctionDecorator:
    def __init__(self, enableCache=True):
        self.enableCache = enableCache

    def __call__(self, wrapper):
        def numericalmathfunction(*args, **kwargs):
            func = specialfunction(wrapper(*args, **kwargs))
            """
            Do some setup to func with decorator arguments (e.g. enableCache)
            """
        return numericalmathfunction

@NumericalMathFunctionDecorator(enableCache=True)
class Wrapper:
    places = ['home', 'office']
    configs = {
               'home':
                  {
                   'attr1': 'path/at/home',
                   'attr2': 'jhdlt'
                  },
               'office':
                  {
                   'attr1': 'path/at/office',
                   'attr2': 'sfgqs'
                  }
              }
    def __init__(self, where='home'):
        # Look for setup configuration on 'Wrapper.configs[where]'.
        assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places)
        self.__dict__.update(Wrapper.configs[where])

    def __call__(self, X):
        """Do stuff with X and return the result
        """
        return X ** 2

model = Wrapper()

当我实例化Wrapper类(#1)时,我收到以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a99bd3d544a3> in <module>()
     15         assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places)
     16 
---> 17 model = Wrapper()

<ipython-input-5-a99bd3d544a3> in numericalmathfunction(*args, **kwargs)
      5     def __call__(self, wrapper):
      6         def numericalmathfunction(*args, **kwargs):
----> 7             func = wrapper(*args, **kwargs)
      8         return numericalmathfunction
      9 

<ipython-input-5-a99bd3d544a3> in __init__(self, where)
     13     def __init__(self, where='home'):
     14         # Look for setup configuration on 'Wrapper.configs[where]'.
---> 15         assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places)
     16 
     17 model = Wrapper()

AttributeError: 'function' object has no attribute 'places'

我想,对于装饰器,Wrapper成为一个无法访问其属性的函数......

关于如何解决这个问题的任何想法?也许有一种解决方法

1 个答案:

答案 0 :(得分:1)

您使用Wrapper函数对象替换了numericalmathfunction(这是一个类)。该对象没有任何类属性,没有。

本质上,装饰者这样做:

class Wrapper:
    # ...

Wrapper = NumericalMathFunctionDecorator(enableCache=True)(Wrapper)

所以无论NumericalMathFunctionDecorator.__call__方法返回什么,现在都替换了类;所有对Wrapper的引用现在引用该返回值。当您在Wrapper方法中使用名称__init__时,您将引用该全局,而不是原始类。

您仍然可以使用type(self)访问当前的类,或者只是通过self引用这些属性(其中名称查找将通过该类):

def __init__(self, where='home'):
    # Look for setup configuration on 'Wrapper.configs[where]'.
    assert where in self.places, "Only valid places are {}".format(self.places)
    self.__dict__.update(self.configs[where])

def __init__(self, where='home'):
    # Look for setup configuration on 'Wrapper.configs[where]'.
    cls = type(self)
    assert where in cls.places, "Only valid places are {}".format(cls.places)
    self.__dict__.update(cls.configs[where])

在这两种情况下,如果你曾经做过子类Wrapper,你最终可能会引用一个子类的属性(在这种情况下你无法做到这一点,因为你必须从装饰器闭包中取出类)

或者,您可以将原始类存储为返回函数的属性:

def __call__(self, wrapper):
    def numericalmathfunction(*args, **kwargs):
        func = specialfunction(wrapper(*args, **kwargs))
        """
        Do some setup to func with decorator arguments (e.g. enableCache)
        """
    numericalmathfunction.__wrapped__ = wrapper
    return numericalmathfunction

然后在__init__中使用该引用:

def __init__(self, where='home'):
    # Look for setup configuration on 'Wrapper.configs[where]'.
    cls = Wrapper
    while hasattr(cls, '__wrapped__'):
        # remove any decorator layers to get to the original
        cls = cls.__wrapped__
    assert where in cls.places, "Only valid places are {}".format(cls.places)
    self.__dict__.update(cls.configs[where])