__get __ () Method

Look at the source code, I noticed this magic method

 1 class A(object):
 2     def __init__(self):
 3         self.name = 'mod'
 4 
 5     def __get__(self, instance, owner):
 6         print(instance, '=====', owner)
 7         return self
 8 
 9 
10 class B(object):
11     a = A()
12 
13 
14 class C(object):
15     d = A()
16 
17     def __init__(self):
18         self.a = A()
19 
20 
21 b = B()
22 c = C()
23 
24 print(B.a)
25 # None ===== <class '__main__.B'>
26 # <__main__.A object at 0x7f0485e519b0>
27 
28 print(b.a)
29 # <__main__.B object at 0x7f0484825b70> ===== <class '__main__.B'>
30 # <__main__.A object at 0x7f0485e519b0>
31 
32 print(b.a.name)
33 # <__main__.B object at 0x7f0484825b70> ===== <class '__main__.B'>
34 # mod
35 
36 print(c.a)
37 # <__main__.A object at 0x7f0485e33208>
38 
39 print(c.d)
40 # _main__.C object at 0x7f0484825b38> ===== <class '__main__.C'>
41 # <__main__.A object at 0x7f0484825c18>

Turn Summary:

First printing, by calling class attribute class, the print result, instance to None, be appreciated that the first parameter is an example of calling a get method of the method, the second class of the instance belongs

Second printing, by calling the class attribute instance, print result confirms the above conclusion

The third printing, the property is normally available only to prove

Fourth printing by calling as an example of an instance attribute A (), and found no trigger __get__ method described __get__ method is only as a class property will only be triggered when

The fifth printing, proof of these conclusions

In addition, __ get__ method must take two arguments, it is mandatory to carry is called, or will be given as follows:

TypeError: __get__() takes 2 positional arguments but 3 were given

So this method is dim at it, in fact pretty much play, I can think of is a kind of chaos may limit other calls, such as determining the class as class attributes of the class is not what we expect of the class, if not, it returns null.

Guess you like

Origin www.cnblogs.com/haiton/p/11026934.html