[英]Why is property.fget a read-only attribute?
我目前正在從庫中修補類的屬性,以使其更加通用。
我正在使用以下代碼執行此操作:
_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函數以便保留docstring,那就更好了:
_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
嘗試分配給它時的TypeError: readonly attribute
)。 我很好奇,如果有一個特殊的原因,或者python開發人員只是認為在創建它之后修改屬性沒有用新的替換它是沒有意義的。
你可能是對的,只是將這些屬性設為只讀的慣例,選擇這些屬性使屬性“全有或全無”。 似乎更多的是“Pythonic”允許在事后分配它們,但是在Python 2.2發行說明中沒有找到基本原理(當引入屬性時)。
在Objects / descrobject.c中 ,屬性的成員屬性被定義為只讀:
static PyMemberDef property_members[] = {
{"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
{"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY},
{"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY},
{"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY},
{0}
};
另外:如果用0
替換READONLY
並編譯,那么只需要分配fget, fset, ..
:
class Test(object):
def __init__(self):
self.flag = True
prop = property(lambda self: self.flag)
obj = Test()
print obj.prop
Test.prop.fget = lambda self: not self.flag
print obj.prop
輸出:
True
False
在IDLE shell中使用Anaconda 2.3.0(Python 3.4.3)進行了測試
>>> p = property()
>>> p.fget
>>> p.__init__( lambda obj: None )
>>> p.fget
<function <lambda> at 0x0121FF18>
>>> p.fget = lambda obj: None
Tracebabk (most recent call last):
File "<pyshell#19>", line 1, in <module>
p.fget = lambda obj: None
AttributeError: readonly attribute
>>>
對我來說看起來並不那么簡單;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.