Public attributes with really private data

Mark Summerfield list at qtrac.plus.com
Fri May 8 09:17:28 EDT 2009


On 8 May, 13:56, Peter Otten <__pete... at web.de> wrote:
> MarkSummerfieldwrote:
> > On 8 May, 08:19, Peter Otten <__pete... at web.de> wrote:
> >> MarkSummerfieldwrote:
> >> > I had a quick search & didn't find anything _nice_ that produced
> >> > attributes with really private data, so I came up with a possible
> >> > solution---for Python 3.
>
> >> Do really you think what you suggest below is "nice"?
>
> > Well the code isn't ugly and doesn't mess with the call stack etc.
>
> >> By the way, your Attribute descriptor stores the value for all instances
> >> of A in the same variable...
>
> > It seems like it does, but it doesn't. The hidden_value is an instance
> > variable that is created every time an Attribute object is created.
>
> >>>> from Attribute import *
> >>>> class A:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
> >>>> class B:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
> >>>> a = A()
> >>>> b = B()
> >>>> a.a,a.b,b.a,b.b
> > (5, 5, 5, 5)
> >>>> a.a=1;a.b=2;b.a=3;b.b=4
> >>>> a.a,a.b,b.a,b.b
> > (1, 2, 3, 4)
>
> But attribute values are shared between all instances of the same class:
>
> >>> class A:
>
> ...     x = Attribute("x", 42, lambda *a: True)
> ...>>> a = A()
> >>> b = A()
> >>> a.x, b.x
> (42, 42)
> >>> a.x = "yadda"
> >>> a.x, b.x
>
> ('yadda', 'yadda')
>
> Peter

Yes. I did think of trying to create the closures dynamically the
first time the getter or setter was called---but that _is_ getting
ugly, so I'll give it up:-)

Thanks!

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Programming in Python 3" - ISBN 0137129297



More information about the Python-list mailing list