Risposte:
Ci sono funzioni integrate chiamate getattresetattr
getattr(object, attrname)
setattr(object, attrname, value)
In questo caso
x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)
df1e una variabile x = 'df1'cioè df1 come stringa in var x. voglio stampare la forma di df in questo modo getattr(x, 'shape')o getattr('df1', 'shape'). So che questo non può essere fatto con getattr, nessun altro metodo.
getattr(globals()[x], 'shape')
newmodulo che è stato deprecato nel 2008 .Esistono funzioni integrate in python 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
Se vuoi mantenere la logica nascosta all'interno della classe, potresti preferire utilizzare un metodo getter generalizzato in questo modo:
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
def get(self,varname):
return getattr(self,varname)
t = Test()
x = "attr1"
print ("Attribute value of {0} is {1}".format(x, t.get(x)))
Uscite:
Attribute value of attr1 is 1
Un altro approccio che potrebbe nasconderlo ancora meglio sarebbe usare il metodo magico __getattribute__, ma ho continuato a ottenere un ciclo infinito che non ero in grado di risolvere quando provavo a recuperare il valore dell'attributo all'interno di quel metodo.
Si noti inoltre che è possibile utilizzare in alternativa vars(). Nell'esempio di cui sopra, si potrebbe scambiare getattr(self,varname)per return vars(self)[varname], ma getattrpotrebbe essere preferibile in base alla risposta alla Qual è la differenza tra varse setattr? .