Public attributes with really private data

Peter Otten __peter__ at web.de
Fri May 8 08:56:53 EDT 2009


Mark Summerfield wrote:

> 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




More information about the Python-list mailing list