Private attribute

castironpi castironpi at gmail.com
Mon Aug 25 15:42:33 EDT 2008


On Aug 25, 2:09 pm, Ken Starks <stra... at lampsacos.demon.co.uk> wrote:
> Ken Starks wrote:
> > I have a class with an attribute called 'gridsize' and I want
> > a derived class to force and keep it at 0.8 (representing 8mm).
>
> > Is this a correct, or the most pythonic approach?
>
> > ####################
>
> >     def __getattr__(self,attrname):
> >         if attrname == 'gridsize':
> >             return 0.8
>
> >     def __setattr__(self,attrname,value):
> >         if attrname == 'gridsize':
> >             pass
> >         else:
> >             self.__dict__[attrname]=value
>
> > #####################
>
> > Cheers,
> > Ken.
>
> Perhaps I should mention the alternative I had in mind:
>
> ###################
>
> class xyz:
>    def __init__(self):
>      self.__dict__['a'] = 123
>      self.b=456
>
>    def __setattr__(self,attrname,value):
>          if attrname == 'a':
>              pass
>          else:
>              self.__dict__[attrname]=value
>
>    # __getattr__() not redefined.
>
> ############################

This is just me, but I don't think that Python is the right language
for your program.  In Python it's extra easy to get around that
obstacle.  Python is more about freedom and discipline.



More information about the Python-list mailing list