Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - why is read-only property writable?

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?

like image 405
imyousuf Avatar asked Mar 17 '13 07:03

imyousuf


People also ask

What is read-only property in Python?

Summary. If you need to make a read-only attribute in Python, you can turn your attribute into a property that delegates to an attribute with almost the same name, but with an underscore prefixed before the its name to note that it's private convention.

Are read-only list which Cannot be modified in Python?

Tuples are, for most intents and purposes, 'immutable lists' - so by nature they will act as read-only objects that can't be directly set or modified.

What does read-only property mean?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.

Are read-only lists which Cannot be modified?

A read-only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using the get method or by using the Iterator of List, This kind of List is good for a certain requirement where parameters are final and can not be changed.


2 Answers

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
like image 99
NPE Avatar answered Oct 04 '22 11:10

NPE


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).

like image 33
BrenBarn Avatar answered Oct 04 '22 12:10

BrenBarn