2016-03-22 10 views
0

変数からオブジェクトを呼び出そうとしています。 getattrを使って変数を使ってオブジェクトの関数を呼び出す方法を知っていますが、変数を使ってオブジェクト名を定義する方法はありません。私はいくつかのサンプルコードの下にドラッグしていますPython - 変数を使用してオブジェクトを呼び出す

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"? 

答えて

1

object_1以来とobjectはグローバル変数であり、あなたは以下のコードを使用することができます:

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

またはこの:

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

globals()['object']は「object_1」を表します。 ng

globals()[globals()['object']]は、object_1オブジェクトを表します。

関連する問題