2016-02-10 16 views
6

Quando si imposta un attributo, del risultato id del risultato viene modificato in valore id. Quando si imposta un metodo, il risultato getattrid non cambia. Perché?Perché setattr funziona in modo diverso per attributi e metodi?

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 
+3

in Python 3 – Lol4t0

risposta

3

La differenza è basata su come metodi funzionano in python

nota che

>>> B.b 
<unbound method B.<lambda>> 

I metodi sono in realtà costruiti utilizzando descriptors

Aggiornamento del "metodo", l'isn descrittore' t che cambia

Guardando dentro il descrittore noi f ind la funzione sottostante fa

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's our new lambda 

Si può anche dare un'occhiata a

B.__dict__['b'] 

prima e dopo

Non
+0

Grazie mille! Questo è quello che stavo cercando. – Timur

+0

Prego. Potrebbe essere d'aiuto agli altri se contrassegni la risposta come "accettata" – second

Problemi correlati