Although the accepted anwer is present, I would like to add a little description.
Do a little exercise
first define the class as follows:
class A: temp='Skyharbor' def __init__(self, x): self.x=x def change(self, y): self.temp=y
So what do we have here?
- We have a very simple class that has the
temp attribute, which is a string - Init method that sets
self.x - The change method sets self.temp
Pretty far ahead? Now let's start playing with this class. Initialize this class first:
a = A('Tesseract')
Now do the following:
>>> print a.temp Skyharbor >>> print A.temp Skyharbor
Well, a.temp worked as expected, but how the hell did a.temp ? Well, that worked because temp is a class attribute. Everything in python is an object. Here A is also an object of class type . Thus, the temp attribute is an attribute belonging to class A, and if you change the temp value through A (and not through instance a), the changed value will be reflected in the entire instance of class A. Release and do the following:
>>> A.temp = 'Monuments' >>> print A.temp Monuments >>> print a.temp Monuments
Interesting, right? And note that id (a.temp) and id (A.temp) are all the same
Any Python object is automatically assigned a dict attribute that contains its list of attributes. Let's look at what this dictionary contains for our objects:
>>> print A.__dict__ { 'change': <function change at 0x7f5e26fee6e0>, '__module__': '__main__', '__init__': <function __init__ at 0x7f5e26fee668>, 'temp': 'Monuments', '__doc__': None } >>> print a.__dict__ {x: 'Tesseract'}
Note that the temp attribute is listed among class A attributes, while x is specified for the instance
So, how did it happen that we got a certain a.temp value, if it is not even specified for an instance of a. Good thing the magic of the __getattribute__() method. In Python, the point syntax automatically calls this method, so when we write a.temp , Python does. getattribute ('temp'). This method performs an attribute search action, i.e. Finds the value of an attribute by browsing in different places.
The standard implementation of __getattribute__() first looks for the internal dictionary ( dict ) of the object, and then the type of the object itself. In this case, a.__getattribute__('temp') executes the first a.__dict__['temp'] and then a.__class__.__dict__['temp']
Now let's use our change method:
>>> a.change('Intervals') >>> print a.temp Intervals >>> print A.temp Monuments
Now that we have used self, print a.temp gives us a different value from print a.temp .
Now, if we compare id (a.temp) and id (A.temp), they will be different