python - 为什么只读属性可写? [英] python - why is read-only property writable?
问题描述
我试图在 Python 中定义一个具有只读属性的类;我遵循了 Python 文档并提出了以下代码:
I am trying to define a class with a read-only property in a Python; I followed Python documentation and came up with the following code:
#!/usr/bin/python
class Test:
def __init__(self, init_str):
self._prop = init_str
@property
def prop(self):
return self._prop
t = Test("Init")
print t.prop
t.prop = "Re-Init"
print t.prop
现在,当我尝试执行代码时,虽然我期待错误/异常,但我看到它正常执行:
Now when I try to execute the code though I am expecting error/exception I see it getting executed normally:
$ ./python_prop_test
Init
Re-Init
我的 Python 版本是 2.7.2.我所看到的,是预期的吗?如何确保属性不可设置?
My Python version is 2.7.2. What I am seeing, is it expected? How do make sure a property is not settable?
推荐答案
为了让这个如你所愿,Test
需要是一个新风格的类:
For this to work as you expect, Test
needs to be a new-style class:
class Test(object):
^^^^^^^^
这在 property() 文档代码>
:
返回新样式类(派生自object
的类)的属性属性.
Return a property attribute for new-style classes (classes that derive from
object
).
当我把 Test
变成一个新样式的类,并试图改变 prop
时,我得到一个异常:
When I turn Test
into a new-style class, and attempt to change prop
, I get an exception:
In [28]: t.prop='Re-Init'
AttributeError: can't set attribute
这篇关于python - 为什么只读属性可写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!