Python provides us many possibilities on instance/class attribute, for example:
class A(object):
def __init__(self):
self.foo = "hello"
a = A()
There are many ways to access/change the value of self.foo:
direct access a.foo
inner dict a.__dict__['foo']
get and set a.__get__ and a.__set__,of course there two are pre-defined methods.
getattribute a.__getattribute__
__getattr__ and __setattr__
maybe more.
While reading source code, I always get lost of what's their ultimate access order? When I use a.foo, how do I know which method/attribute will get called actually?
解决方案
bar = a.foo...
invokes a.__getattribute__('foo')
which in turn by default looks up a.__dict__['foo']
or invokes foo's .__get__() if defined on A.
The returned value would then be assigned to bar.
a.foo = bar...
invokes a.__getattribute__('foo')
which in turn by default looks up a.__dict__['foo']
or invokes foo's .__set__(bar) if defined on A.