using __getitem()__ correctly

Charles T. Smith cts.private.yahoo at gmail.com
Thu Dec 31 07:45:55 EST 2015


On Wed, 30 Dec 2015 17:31:11 -0700, Ian Kelly wrote:

>> In any case, I thought that class attributes were, in fact, items of
>> __dict__?
> 
> That's correct, but as I said in my previous message, self.attrs and
> self.attrs.__dict__ are two different dicts, and you're confusing one
> for the other. Maybe this will be illuminating:
> 
>>>> class mydict(dict): pass
> ...
>>>> md = mydict()
>>>> md['foo'] = 42  # Set an item in md
>>>> md['foo']  # 'foo' exists as an item
> 42
>>>> md.foo  # but not as an attribute
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'mydict' object has no attribute 'foo'
>>>> md.__dict__['foo']  # and it's not in md.__dict__
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: 'foo'
>>>> md.bar = 43  # Set an attribute on md md.bar  # 'bar' exists as an
>>>> attribute
> 43
>>>> md.__dict__['bar']  # and it's in md.__dict__
> 43
>>>> md['bar']  # but it's not in md itself
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: 'bar'
> 
> And to hopefully drive the point home:
> 
>>>> md.items()
> [('foo', 42)]
>>>> md.__dict__.items()
> [('bar', 43)]


Okay, I think I got an important point that you said earlier but
I didn't get the full ramifications thereof:

  class md (... more about this ...):
      pass

  md is a class that has an dictionary attribute __dict__:
  - md['level1'] puts attributes in md
  - md.level2 puts attributes in md.__dict__

is that correct?

Now, as to the superclass, if that's, say, object, then
it has two levels:

  md -> object (containing a dict)

if the superclass is dict, then it only has one level:

  md -> dict

I'll have to look at my methods again with those understandings.



More information about the Python-list mailing list