Chris Angelico <[email protected]> wrote:
> On Thu, Oct 27, 2011 at 10:03 PM, Duncan Booth
><[email protected]> wrote:
>> Types without a __dict__ use less memory. Also, if you couldn't have a
>> type that didn't have a `__dict__` then any `dict` would also need its
>> own `__dict__` which would either result in infinite memory use or
>> recursive dictionaries.
>>
>
> Easy, just self-reference.
> a = {}
> a.__dict__ is a --> True
>
> Yeah, it's recursion, but no different from types:
>
Try thinking that one through. Imagine you could set up a dictionary the
way you describe:
>>> class DictWithDict(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
self.__dict__ = self
>>> d = DictWithDict()
>>> d.keys()
dict_keys([])
>>> d = DictWithDict({'a': 42})
>>> d.keys()
dict_keys(['a'])
>>> d['keys'] = lambda: 'oops'
>>> d.keys()
'oops'
>>>
A dict with itself as its own __dict__ becomes like a javascript object
where subscripting and attribute access are mostly interchangeable.
--
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list