2016-03-22 11 views
0

Ich versuche, ein Objekt aus einer Variablen aufzurufen. Ich weiß, wie man getattr benutzt, um eine Funktion eines Objekts mit einer Variablen aufzurufen, kann aber nicht herausfinden, wie man eine Variable benutzt, um den Objektnamen zu definieren. Ich habe einige Beispiel-Code unten gezogen:Python - Verwenden Variable zum Aufruf des Objekts

class my_class(object): 
    def __init__(self, var): 
     self.var1 = var 

var = "hello" 
object_1 = my_class(var) 

print object_1.var1 # outputs - hello 

attribute = "var1" 

# i can call the attribute from a variable 

print getattr(object_1, attribute) # outputs - hello 

object = "object_1" 

# but i do not know how to use the variable "object" defined above to call the attribute 

# now i have defined the variables object and attribute how can i use them to output "hello"? 

Antwort

1

Seit object_1 und object sind globale Variablen, Sie den Code unten verwenden:

print(globals()[globals()['object']].var1) # "hello" is printed 

oder dies:

print(getattr(globals()[globals()['object']], attribute)) # "hello" is printed 

wo

globals()['object'] repräsentiert "object_1" stri ng

globals()[globals()['object']] steht für object_1 Objekt.

Verwandte Themen