By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,532 Members | 1,527 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,532 IT Pros & Developers. It's quick & easy.

Readonly attributes ...

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.