What is the difference in Python between creating an attribute and declaring it in a class?

These two codes will produce two different outputs, why?

class Test: def __get__(self, instance, owner): return 42 def __set__(self, instance, value): pass class A: a = Test() a = A() print(aa) // print 42 aa = 0 print(aa) // print 42 

and

 class Test: def __get__(self, instance, owner): return 42 def __set__(self, instance, value): pass class A: pass a = A() aa = Test() print(aa) // print <__main__.Test object at 0xb700d6cc> aa = 0 print(aa) // print 0 

How are attributes stored in the Python engine?

+4
source share
2 answers

Your Test class is not called an "attribute", it is a descriptor . Descriptors work, by definition, only when stored in a class (new style, for poor Python 2 users). Non-class object descriptor objects have no special meaning; they are treated like any other object. Their __get__ method __get__ ignored when they are restored, and their __set__ ignored when they are replaced.

+2
source

In the first case, the Test class has a handle for your class A, since it defines the __get__ and __set__ .

If you use any class with __get__ , __set__ methods, as an attribute of your class, it acts as a descriptor for your class, and not as an attribute .
So, when you assign something to this variable, the descriptor's __set__ method is __set__ , and when you try to access it, the descriptor's __get__ method is __get__ . Descriptors simply provide access to class attributes through getters and setters

So, when you do a = Test() in your class A, the __get__ descriptor method is __get__ , and it is set to 42 .

While in the second case, you create a class Test in the same way as every other class. So aa represents a reference to an instance of the Test class.

0
source

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


All Articles