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.
__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.
__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__ .
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.
__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 .
__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
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With