Zope:无法在属性装饰器下访问REQUEST


问题内容

我试图在类中使用属​​性装饰器。虽然它本身运作良好,但我无法使用任何必须访问的代码REQUEST

class SomeClass():
   #Zope magic code
   _properties=({'id':'someValue', 'type':'ustring', 'mode':'r'},)

  def get_someValue(self):
    return self.REQUEST

  @property
  def someValue(self):
    return self.REQUEST

尽管致电get_someValue给我带来了理想的结果,但是尝试访问someValue会引发AttributeError

这种行为背后的逻辑是什么?有没有办法解决这个限制?

(我正在使用Zope 2.13.16,Python 2.7.3)


问题答案:

property装饰只适用于
新的风格 类;
也就是说,继承自的类objectREQUEST另一方面,获取(通过属性访问使您可以访问全局对象)是非常“老套”的python,两者不能很好地协同工作,因为property
忽略 了获取REQUEST对象所需的获取包装器。


Zope有自己的property类似方法,可以在新型类之前进行修饰,而装饰器property称为ComputedAttribute,实际上可以在property装饰器和新类上进行许多年的修饰。但是,ComputedAttribute-wrapped函数确实知道如何与Acquisition-wrapped对象一起工作。

您可以ComputedAttibuteproperty装饰器一样使用:

from ComputedAttribute import ComputedAttribute

class SomeClass():   
    @ComputedAttribute
    def someProperty(self):
        return 'somevalue'

ComputedAttribute包装函数也可以用包装的水平,这是我们需要采集的包装打交道时进行配置。ComputedAttribute在这种情况下,您不能将用作装饰器:

class SomeClass():   
    def someValue(self):
        return self.REQUEST
    someValue = ComputedAttribute(someValue, 1)

定义一个新函数来为我们做装饰是很容易的:

from ComputedAttribute import ComputedAttribute

def computed_attribute_decorator(level=0):
    def computed_attribute_wrapper(func):
        return ComputedAttribute(func, level)
    return computed_attribute_wrapper

将其放在实用程序模块中的某个位置,然后可以将其用作可调用的修饰符,以将某些内容标记为“采集感知”属性:

class SomeClass(): 
    @computed_attribute_decorator(level=1)
    def someValue(self):
        return self.REQUEST

请注意,与不同propertyComputedAttribute只能用于吸气剂;不支持设置器或删除器。