Readonly attributes ...

Larry Bates lbates at swamisoft.com
Mon Mar 29 10:14:22 EST 2004


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" <kobayashi at netcourrier.com> wrote in message
news:fe8d7286.0403290133.15ee661f at posting.google.com...
> 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.





More information about the Python-list mailing list