python - why is read-only property writable?

旧城冷巷雨未停 提交于 2020-01-12 06:48:13

问题


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

My Python version is 2.7.2. What I am seeing, is it expected? How do make sure a property is not settable?


回答1:


For this to work as you expect, Test needs to be a new-style class:

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

This is hinted at in the documentation for property():

Return a property attribute for new-style classes (classes that derive from object).

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



回答2:


To use properties you must use new-style classes. To use new-style classes in Python 2 you must inherit from object. Change your class def to class Test(object).



来源:https://stackoverflow.com/questions/15458613/python-why-is-read-only-property-writable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!