【发布时间】:2011-08-11 13:20:00
【问题描述】:
我目前正在修补库中的一个类的属性,以使其更加通用。
我正在使用以下代码执行此操作,效果很好:
_orig_is_xhr = BaseRequest.is_xhr.fget
_orig_is_xhr_doc = BaseRequest.is_xhr.__doc__
BaseRequest.is_xhr = property(lambda self: _orig_is_xhr(self) or
'_iframe-xhr' in request.form, doc=_orig_is_xhr_doc)
但是,如果我可以简单地覆盖 getter 函数以便保留文档字符串,那就更好了:
_orig_is_xhr = BaseRequest.is_xhr.fget
BaseRequest.is_xhr.fget = lambda self: (_orig_is_xhr(self) or
'_iframe-xhr' in request.form)
这不起作用,因为property.fget 是一个只读属性(TypeError: readonly attribute 尝试分配给它时)。
我很好奇这是否有特殊原因,或者 python 开发人员只是认为在创建属性后修改属性而不用新属性替换它是没有意义的。
【问题讨论】:
标签: python properties