Setting a read-only attribute
James Stroud
jstroud at mbi.ucla.edu
Thu Aug 30 21:21:42 EDT 2007
tleeuwenburg at gmail.com wrote:
> I have an object and wish to set an attribute on it which,
> unfortunately for me, is read-only.
>
> How can I go about this?
Can you simply subclass the object's class, intercept __setattr__ and
__getattribute__, and spoof the read-only attribute? E.g.:
class A(object):
def get_ro(self):
return 'readonly'
ro = property(get_ro)
class B(A):
def __setattr__(self, anatt, aval):
if anatt == 'ro':
anatt = '_ro'
super(A, self).__setattr__(anatt, aval)
def __getattribute__(self, anatt):
if anatt == 'ro' and hasattr(self, '_ro'):
anatt = '_ro'
return super(A, self).__getattribute__(anatt)
The output:
py> class A(object):
... def get_ro(self):
... return 'readonly'
... ro = property(get_ro)
...
py> class B(A):
... def __setattr__(self, anatt, aval):
... if anatt == 'ro':
... anatt = '_ro'
... super(A, self).__setattr__(anatt, aval)
... def __getattribute__(self, anatt):
... if anatt == 'ro' and hasattr(self, '_ro'):
... anatt = '_ro'
... return super(A, self).__getattribute__(anatt)
...
py> a = A()
py> print a.ro
readonly
py> a.ro = 4
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.AttributeError'>: can't set attribute
py>
py> b = B()
py> b.x = 10
py> print b.x
10
py> print b.ro
readonly
py> b.ro = 4
py> print b.ro
4
I'm not so sure this is the least clunky way to do this.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list