I think your confusion arises from the fact that straight dot notation (ex a.b.c
) accesses the same parameters as getattr()
, but the parsing logic is different. While they both essentially key in to an object's __dict__
attribute, getattr()
is not bound to the more stringent requirements on dot-accessible attributes. For instance
setattr(foo, 'Big fat ugly string. But you can hash it.', 2)
Is valid, since that string just becomes a hash key in foo.__dict__
, but
foo.Big fat ugly string. But you can hash it. = 2
and
foo.'Big fat ugly string. But you can hash it.' = 2
are syntax errors because now you are asking the interpreter to parse these things as raw code, and that doesn't work.
The flip side of this is that while foo.b.c
is equivalent to foo.__dict__['b'].__dict__['c']
, getattr(foo, 'b.c')
is equivalent to foo.__dict__['b.c']
. That's why getattr
doesn't work as you are expecting.
setattr(a, 'b.c', 2)
. What shouldgetattr(a, 'b.c')
return now? What if there was noc
onb
before? You are allowed to use a.
in attribute names, so you can't expectgetattr
to be able to traverse over objects like this. – Cozeget/setattr
are mapped to magic methods which have single purpose as @ThaneBrimhall said it's the dictionary lookup. For me this is JavaScript related thing where.
operator is just syntax sugar forobj['@ttr1but3']
(obj
doesn't have to be a mapping). Python' equivalent of this isgetattr
. Read about__dict__
and try to override__getattribute__
to grasp it yourself. – Cholecystectomygetattr()
andsetattr()
are not mapped to magic methods, not directly. The__getattribute__
,__getattr__
and__setattr__
special methods are hooks that, if defined, Python will call for attribute access.getattr()
andsetattr()
are translations of theobject.attr
expression andobject.attr = ...
assignment statements that incidentally let you go beyond Python identifiers in the attribute name. And not all Python objects have a__dict__
mapping either, so to say it's a straightforward dictionary lookup is also too simplistic. – Coze__slots__
. Mentioning magic methods as hooks really improved my understanding. – Cholecystectomy