Created
August 22, 2010 13:12
-
-
Save seanh/543749 to your computer and use it in GitHub Desktop.
Read-only attributes in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| In [1]: class Foo: | |
| ...: def __init__(self,x): | |
| ...: self._x = x | |
| ...: def getx(self): | |
| ...: return self._x | |
| ...: x = property(getx) | |
| ...: | |
| ...: | |
| In [2]: f = Foo(5) | |
| In [3]: f.x | |
| Out[3]: 5 | |
| In [4]: f.x = 6 | |
| In [5]: f.x | |
| Out[5]: 6 | |
| In [6]: f._x | |
| Out[6]: 5 | |
| In [7]: class Foo(object): | |
| ...: def __init__(self,x): | |
| ...: self._x = x | |
| ...: def getx(self): | |
| ...: return self._x | |
| ...: x = property(getx) | |
| ...: | |
| ...: | |
| In [8]: f = Foo(5) | |
| In [9]: f.x | |
| Out[9]: 5 | |
| In [10]: f.x = 6 | |
| --------------------------------------------------------------------------- | |
| AttributeError Traceback (most recent call last) | |
| /home/seanh/<ipython console> in <module>() | |
| AttributeError: can't set attribute | |
| In [11]: |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To create a read-only attribute in Python you simply use the
propertybuilt-in and pass anfgetparameter but not anfset. Now if user code tries to set the value of the read-only attributeAttributeErrorwill be raised.What confused me for ages is that for
property()to work properly the class has to be a new-style class, i.e. it has to inherit fromobject. (I think in Python 3 maybe all classes will inherit fromobjectimplicitly, like in Java.)In the first attempt above
Foois an old-style class, and the read-only attribute doesn't work as expected, writing the attribute produces unexpected behaviour. In the second attemptFooinherits fromobject, and attempting to write the read-only attribute raises an exception.Also see: Properties: attributes managed by get/set methods from Guido's article Unifying types and classes in Python 2.2.