简体   繁体   English

python - 为什么只读属性可写?

[英]python - why is read-only property writable?

I am trying to define a class with a read-only property in a Python; 我试图在Python中定义一个只读属性的类; I followed Python documentation and came up with the following code: 我按照Python文档编写了以下代码:

#!/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

My Python version is 2.7.2. 我的Python版本是2.7.2。 What I am seeing, is it expected? 我所看到的,是否有望? How do make sure a property is not settable? 如何确保房产不可设置?

For this to work as you expect, Test needs to be a new-style class: 为了使其按预期工作, Test需要是一个新式的类:

class Test(object):
          ^^^^^^^^

This is hinted at in the documentation for property() : 这在property()文档中暗示:

Return a property attribute for new-style classes (classes that derive from object ). 返回新样式类的属性属性(从object派生的类)。

When I turn Test into a new-style class, and attempt to change prop , I get an exception: 当我将Test变成一个新式的类,并试图改变prop ,我得到一个例外:

In [28]: t.prop='Re-Init'

AttributeError: can't set attribute

To use properties you must use new-style classes. 要使用属性,必须使用新式类。 To use new-style classes in Python 2 you must inherit from object . 要在Python 2中使用新式类,必须从object继承。 Change your class def to class Test(object) . 将类def更改为class Test(object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM