470,815 Members | 3,017 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,815 developers. It's quick & easy.

Readonly attributes ...

Hi all python users,

A question about readonly attributes once again, but
even reading the threads about "properties" and "descriptors",
I can't find exactly what I want.

Let a developper to write the class

class A(object):
def __init__(self):
self.x = 1
self.setX(2)
return
def getX(self):
return self.__x
def setX(self, value):
self.__x = value
return
x = property(getX, setX)
pass

Of course, the developper can set the attribute 'x'
in the class ...

Now, the user part :

a = A()
print a.x
a.x = 1 # I want this operation to raise
print a.x
a.setX(23) # I want this operation to raise too !!
print a.getX()

I can't find a way to do that ... but may be I've
missed something !

Cheers,

K.
Jul 18 '05 #1
1 1338
It is cumbersome but you can do it as follows:

class A:
_ROattributes=['x', '_A__x']

def __init__(self):
#self.x = 1
self.__dict__['x']=1 # Sets x without calling __setattr__
self.__setX(2)
return

def getX(self):
return self.__x
#
# Use name mangling to hide setX (by renaming to __setX)
# to outside execution. Isn't perfect, but follows convention.
#
def __setX(self, value):
self.__dict__['_A__x'] = value
return

def __setattr__(self, key, value):
#print "in __setattr__, key=",key
if key in self._ROattributes:
print "Read Only attribute %s, not set" % key

else:
self.__dict__[key]=value

#x = property(getX, setX)
#pass

a=A()
print "a.x=", a.x
a.x=1
a._A__setX(23) # You can call it if you REALLY try
print a.getX()


-Larry Bates

"kobayashi" <ko*******@netcourrier.com> wrote in message
news:fe**************************@posting.google.c om...
Hi all python users,

A question about readonly attributes once again, but
even reading the threads about "properties" and "descriptors",
I can't find exactly what I want.

Let a developper to write the class

class A(object):
def __init__(self):
self.x = 1
self.setX(2)
return
def getX(self):
return self.__x
def setX(self, value):
self.__x = value
return
x = property(getX, setX)
pass

Of course, the developper can set the attribute 'x'
in the class ...

Now, the user part :

a = A()
print a.x
a.x = 1 # I want this operation to raise
print a.x
a.setX(23) # I want this operation to raise too !!
print a.getX()

I can't find a way to do that ... but may be I've
missed something !

Cheers,

K.

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Michael SL | last post: by
2 posts views Thread by Raed Sawalha | last post: by
2 posts views Thread by SivaprakashShanmugam | last post: by
1 post views Thread by Thierry | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.