Difference between __getattribute__ and obj .__ dict __ ['x'] in python?

I understand that in python, whenever you access a class / instance variable, it calls the __getattribute__ method to get the result. However, I can also use obj.__dict__['x'] directly and get what I want.

I'm a little confused, what's the difference? Also, when I use getattr(obj, name) , does it call __getattribute__ or obj.__dict__[name] internally?

Thanks in advance.

+5
source share
3 answers

__getattribute__() method is designed to handle lower-level attributes.

The default implementation tries to find the name in the internal __dict__ (or __slots__ ). If the attribute is not found, it calls __getattr__() .

UPDATE (as in the comment):

These are different ways of finding attributes in a Python data model. They are internal methods designed to be replaced correctly in any possible situation. Hint: "The mechanism is in object.__getattribute__() , which converts bx to type(b).__dict__['x'].__get__(b, type(b)) ." from docs.python.org/3/howto/descriptor.html

+1
source

Not every python object has a dictionary in which its attributes are stored; there are slots, properties and attributes that are calculated are necessary. You can also overwrite __getattribute__ and __getattr__ . Access to an attribute is more complicated than a simple dictionary search. So the usual way to access an attribute is

 obj.x 

wenn you have a variable with the attribute name:

 getattr(obj, name) 

Normally you should not use the __xxx__ internal attributes.

0
source

Attributes in __dict__ are only a subset of all the attributes that an object has.

Consider this class:

 class C: ac = "+AC+" def __init__(self): self.ab = "+AB+" def show(self): pass 

The instance ic = C() this class will have the attributes 'ab' , 'ac' and 'show' (and several others). __gettattribute__ will find them all, but only "ab" is stored in ic.__dict__ . The other two can be found in C.__dict__ .

0
source

Source: https://habr.com/ru/post/1239561/


All Articles