Concise idiom to initialize dictionaries
Caleb Hattingh
caleb1 at telkomsa.net
Thu Nov 11 22:48:33 EST 2004
Steve,
Not only did you answer my silly question, but also the question I
actually wanted to ask ...__getattribute__ is what I was thinking of.
thats cool :)
thx
Caleb
On Thu, 11 Nov 2004 20:30:18 +0000 (UTC), Steven Bethard
<steven.bethard at gmail.com> wrote:
> Caleb Hattingh <caleb1 <at> telkomsa.net> writes:
>>
>> For interest sake, how would such a thing look with new-style classes?
>> My
>> (likely misinformed) impression is that __getattr__ for example, doesn't
>> behave in quite the same way?
>
> Just the same[1] =)
>
>>>> class AllDicts(object):
> ... def __getattr__(self, name):
> ... d = {}
> ... setattr(self, name, d)
> ... return d
> ... def __repr__(self):
> ... items = self.__dict__.items()
> ... items.sort()
> ... return '\n'.join(['%s -> %r' % item for item in items])
> ...
>>>> ad = AllDicts()
>>>> ad.a[1] = 99
>>>> ad.b[2] = 42
>>>> ad.b[3] = 11
>>>> ad
> a -> {1: 99}
> b -> {2: 42, 3: 11}
>>>>
>
> I believe that __getattr__ works just the same (but to check for
> yourself, see
> http://docs.python.org/ref/attribute-access.html). I think what you're
> thinking
> of is __getattribute__ which new-style classes offer *in addition* to
> __getattr__. While __getattr__ is called only if an attribute is not
> found,
> __getattribute__ is called unconditionally for every attribute access.
>
> Steve
>
> [1] modulo my preference for list comprehensions/generator expressions
> instead
> of map
>
More information about the Python-list
mailing list