有沒有辦法在 Python 中使用變量中的字符串調用方法? (Is there a way to call a method in Python using a string inside a variable?)


問題描述

有沒有辦法在 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 GeeThavas Antonio)

參考文件

  1. Is there a way to call a method in Python using a string inside a variable? (CC BY‑SA 2.5/3.0/4.0)

#Variables #Python #methods #list #append






相關問題

使用 htaccess 從基本 URL 中刪除變量 (Remove variable from base URL with htaccess)

如何將解碼的數據包數據和標頭輸出組合到單個變量/字典中以進行字符串搜索 (How to combine decoded packet data and header output into a single variable/dictionary for string searches)

@Ruby on Rails 中的變量 (@ variables in Ruby on Rails)

xslt 將變量發送到另一個模板 (xslt send variable to another template)

變量被評估為任何東西 (Variable Being Evaluated as Anything)

獲取python函數的變量 (Get a variable of python function)

讀取 url JQuery 中的 GET 變量 (read the GET variables in url JQuery)

使用變量名作為數組索引 (Using variable name as array index)

Javascript PHP var數組將雙引號放入 (Javascript PHP var array puts double quotes in)

兩個不同定義之間的變量 (Variable between two different definitions)

Tkinter 組合框 Python (Tkinter Combobox Python)

有沒有辦法在 Python 中使用變量中的字符串調用方法? (Is there a way to call a method in Python using a string inside a variable?)







留言討論