Why does setattr work differently for attributes and methods?

When I set the attribute, the result of getattr id changes to id . When I set the method, the result of getattr id does not change. What for?

 class A (object): a = 1 a = 42 print id(getattr(A, 'a')) print id(a) setattr(A, 'a', a) print id(getattr(A, 'a')) # Got: # 36159832 # 36160840 # 36160840 class B (object): def b(self): return 1 b = lambda self: 42 print id(getattr(B, 'b')) print id(b) setattr(B, 'b', b) print id(getattr(B, 'b')) # Got: # 140512684858496 # 140512684127608 # 140512684858496 
+6
source share
1 answer

The difference is based on how the methods work in python

note that

 >>> Bb <unbound method B.<lambda>> 

In fact, methods are created using

Updating the "method", the handle does not change

Inside the descriptor, we find that the main function performs

 class B (object): def b(self): return 1 b = lambda self: 42 print id(getattr(B, 'b')) print id(b) setattr(B, 'b', b) print id(getattr(B, 'b')) print id(getattr(B, 'b').im_func) # grab function from the descriptor 4424060752 4440057568 4424060752 4440057568 # here our new lambda 

You can also watch

 B.__dict__['b'] 

before and after

+3
source

All Articles