問題描述
有沒有辦法在 Python 中使用變量中的字符串調用方法? (Is there a way to call a method in Python using a string inside a variable?)
我是編碼新手,所以如果這個問題已經在其他地方得到回答,請原諒我,但我試著找了一會兒卻找不到答案。
為了澄清我正在嘗試的問題為了解決,我將用下面的代碼說明它:
#Sample problem
ABCD = []
KEY = "ABCD"
data = 123
[str(KEY)].append(data)
print(f"{ABCD}")
這裡我試圖調用列表 ABCD 的 append 方法,但變量 KEY 包含字符串“ABCD”。此代碼不起作用,但說明了我的問題。我想知道是否可以使用變量而不是硬編碼來調用上述方法,例如:
if KEY == "ABCD":
ABCD.append(data)
print(f"{ABCD}")
謝謝!!
參考解法
方法 1:
I think I shall share my method not using eval
. It accesses all the local variables currently in the script. The program uses this to it's advantage allowing it to locate whether a variable exists or not. Another thing used in this program are dictionaries which help us store our information neatly. Though it might be a tad bit overcomplicated Testcase 1 #ABCD
does exist
ABCD = []
KEY = "ABDC"
data = 123
import sys, pprint
sys.displayhook = pprint.pprint
variables = locals()
check if KEY can be found in locals
if variables.get(KEY) != None:
#create a dict ,KEY = key, "[]" is value
#{'ABCD': []}
varDict = {KEY:variables.get(KEY)}
#append data
varDict[KEY].append(data)
print(varDict)
KEY is not variable in locals
else:
print('could not find')
</code></pre>
expected output
{'ABCD': [123]}
Testcase 2 #ABCD is not existant, instead ABDC
.
ABCD = []
KEY = "ABDC"
data = 123
import sys, pprint
sys.displayhook = pprint.pprint
variables = locals()
#check if KEY can be found in locals
if variables.get(KEY) != None:
#create a dict ,KEY = key, "[]" is value
#{'ABCD': []}
varDict = {KEY:variables.get(KEY)}
#append data
varDict[KEY].append(data)
print(varDict)
#KEY is not variable in locals
else:
print('could not find')
expected output
could not find
Let me know if a test case does not work.
(by Gee、Thavas Antonio)
參考文件