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"
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"
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)
C'è anche delattr per l'eliminazione di attributi, ma questo è usato raramente. –
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
Questo è sicuramente il modo elegante! – larry
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
Duplicate: http://stackoverflow.com/questions/1887509/access-to-class-attributes-by-using-a-variable-in-python –
Eventuali duplicati di [Python: accesso alla proprietà della classe da stringa] (http://stackoverflow.com/questions/1167398/python-access-class-property-from-string) – fejese