2010-04-10 10 views
65

Come impostare/ottenere i valori degli attributi di t forniti da x.Come accedere alla stringa attributo attributo dell'oggetto corrispondente al nome di tale attributo

class test(): 
    attr1 = int 
    attr2 = int 

t = test() 
x = "attr1" 
+2

Duplicate: http://stackoverflow.com/questions/1887509/access-to-class-attributes-by-using-a-variable-in-python –

+1

Eventuali duplicati di [Python: accesso alla proprietà della classe da stringa] (http://stackoverflow.com/questions/1167398/python-access-class-property-from-string) – fejese

risposta

149

C'è built-in funzioni chiamate getattr e setattr

getattr(object, attrname) 
setattr(object, attrname, value) 

In questo caso

x = getattr(t, "attr1") 
setattr(t, 'attr1', 21) 
+5

C'è anche delattr per l'eliminazione di attributi, ma questo è usato raramente. –

+3

e hasattr per testare se un oggetto ha o meno un attr specifico anche se in quel caso l'uso del tre argomento getattr (oggetto, attrname, default) è spesso migliore. – Duncan

+0

Questo è sicuramente il modo elegante! – larry

5

C'è pitone funzioni integrate SetAttr e getattr. Quale può essere usato per impostare e ottenere l'attributo di una classe.

Un breve esempio:

>>> from new import classobj 

>>> obj = classobj('Test', (object,), {'attr1': int, 'attr2': int}) # Just created a class 

>>> setattr(obj, 'attr1', 10) 

>>> setattr(obj, 'attr2', 20) 

>>> getattr(obj, 'attr1') 
10 

>>> getattr(obj, 'attr2') 
20 
Problemi correlati