Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I am a little confused about what is the difference? Also when I use getattr(obj, name), is it calling __getattribute__ or obj.__dict__[name] internally?

Thanks in advance.

like image 399
cizixs Avatar asked Dec 31 '15 08:12

cizixs


People also ask

What is __ Getattribute __ in Python?

__getattribute__This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.

What is the difference between Getattr and Getattribute?

__getattribute__ has a default implementation, but __getattr__ does not. This has a clear meaning: since __getattribute__ has a default implementation, while __getattr__ not, clearly python encourages users to implement __getattr__ .

What is __ module __ in Python?

A module in Python is a file (ending in .py ) that contains a set of definitions (variables and functions) that you can use when they are imported.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .


2 Answers

__getattribute__() method is for lower level attribute processing.

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):

They are different ways for finding attributes in the Python data model. They are internal methods designed to fallback properly in any possible situation. A clue: "The machinery is in object.__getattribute__() which transforms b.x into type(b).__dict__['x'].__get__(b, type(b))." from docs.python.org/3/howto/descriptor.html

like image 109
tuned Avatar answered Oct 11 '22 03:10

tuned


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

Consider this class:

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

    def show(self):
        pass

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

like image 32
VPfB Avatar answered Oct 11 '22 01:10

VPfB