What is the python attribute to get and set the order?

Python provides us with many options for the 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
  • internal dict a.__dict__['foo']
  • get and set a.__get__ and a.__set__ , of course, there are two predefined methods.
  • getattribute a.__getattribute__
  • __getattr__ and __setattr__
  • maybe more.

While reading the source code, I always get lost in what is their final access order? When I use a.foo , how do I know which method / attribute will actually be called?

+6
source share
2 answers

bar = a.foo ...

  • calls a.__getattribute__('foo')
  • which, in turn, by default looks for a.__dict__['foo']
  • or calls foo .__get__() , if defined in A

The return value will then be assigned to bar .


a.foo = bar ...

  • calls a.__getattribute__('foo')
  • which, in turn, by default looks for a.__dict__['foo']
  • or calls foo .__set__(bar) , if defined on A.
+7
source

I found out this wonderful entry, which has a detailed explanation on finding attributes of an object / class.

To search for attributes of an object:

The alleged Class is a class, and instance is an instance of Class , evaluating instance.foobar approximately equal this:

  • Call the type slot for Class.__getattribute__ ( tp_getattro ). The following is executed by default:
    • Does Class.__dict__ a foobar element which is a data descriptor?
      • If so, return the result of Class.__dict__['foobar'].__get__(instance, Class) .
    • Is there an 'foobar' element in instance.__dict__ ?
      • If so, return instance.__dict__['foobar'] .
    • Does Class.__dict__ an foobar element that is not a data descriptor [9]?
      • If so, return the result of Class.__dict__['foobar'].__get__(instance, klass) . [6]
  • If the attribute is still not found and there is Class.__getattr__ , call Class.__getattr__('foobar') .

There is an illustrated image for this:

enter image description here

Please check out the source blog if interested, which gives a great explanation for the python class, attribute lookups and metaclass.

+6
source

All Articles