using __getitem()__ correctly

Charles T. Smith cts.private.yahoo at gmail.com
Thu Dec 31 06:17:31 EST 2015


On Thu, 31 Dec 2015 10:50:53 +1100, Steven D'Aprano wrote:

> I'm not sure what distinction you're referring to, can you explain?

Ian Kelly had said:

>> How precisely are you trying to store these: as an attribute, or as a
>> dict item? If it's supposed to be in the dict, then why is your
>> __getitem__ trying to look up an attribute to begin with?

to which I answered:

>> In any case, I thought that class attributes were, in fact, items of
>>__dict__?

> 
> Obviously there is a syntax difference between x.attr and x['key'], but
> attributes *are* items in a dictionary (ignoring __slots__ and
> __getattr__ for the time being). Either the instance __dict__, the class
> __dict__, or a superclass __dict__.


That was my understanding but I wasn't sure what Ian meant when he went on
to say:

>> If it's supposed to be in the dict, then why is your __getitem__
>> trying to look up an attribute to begin with?

Which raises the question of where they would be if not in a dictionary.

This brings up a fundamental unclarity of mine: an object has attributes, one
of which is __dict__, which has attributes.

- how does one access the attributes in e.g. self
- where do I find the attribute 'mcc' by cruising around in pdb, given
  the objs below?


(PDB)pp dir (self)
['__class__',
 '__cmp__',
 ...
 '__dict__',
  ...
 '__weakref__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'has_key',
 'items',
 'iteritems',
 'iterkeys',
 'itervalues',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

(PDB)pp dir (self.__dict__)
['__class__',
 '__cmp__',
 ...
 '__delitem__',
 '__doc__',
 ...
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'has_key',
 'items',
 'iteritems',
 'iterkeys',
 'itervalues',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

(PDB)pp (self.keys())
['mcc']


It was recommended that I use the obj[name] syntax in __getattr__()
but that then invoked __getitem__(), complicating the matter.


To be specific, if an attribute is not available, I want to assume
it's a graph node and create it.  If the attribute has an index,
I want to create and access an array of those nodes.

It seems to fall perfectly within the definition of __getattr__()
and __getitem__(), but I suspect that slight programming errors
(i.e. mine) are hiding the proper functionality of these methods.


Thanks everybody, for your help so far, and hopefully you can me
pointed in the right direction.

Happy New Year!
cts




More information about the Python-list mailing list