简体   繁体   English

有没有办法使用变量内的字符串调用 Python 中的方法?

[英]Is there a way to call a method in Python using a string inside a variable?

I'm new to coding so please forgive me if this question have already been answered elsewhere, but I tried looking for awhile and couldn't find an answer.我是编码新手,所以如果这个问题已经在其他地方得到回答,请原谅我,但我试着找了一会儿却找不到答案。

To clarify the issue I am trying to solve, I'll illustrate it with the code below:为了澄清我试图解决的问题,我将用下面的代码来说明它:

#Sample problem
ABCD = []
KEY = "ABCD"
data = 123
[str(KEY)].append(data)

print(f"{ABCD}")

Here I am attempting to call the append method for the list ABCD but with the variable KEY which contains the string "ABCD" This code doesn't work but illustrates my question.在这里,我试图为列表 ABCD 调用 append 方法,但使用包含字符串“ABCD”的变量 KEY 此代码不起作用,但说明了我的问题。 I am wondering if it is possible to call the method such as the one I have above using a variable instead of hard coding it like:我想知道是否可以使用变量而不是硬编码来调用我上面的方法,例如:

if KEY == "ABCD":
    ABCD.append(data)

print(f"{ABCD}")

Thank you!!谢谢!!

I think I shall share my method not using eval .我想我会分享我不使用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虽然它可能有点过于复杂 测试用例 1 # ABCD确实存在

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预计 output

{'ABCD': [123]}

Testcase 2 #ABCD is not existant, instead ABDC .测试用例 2 #ABCD 不存在,而是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预计 output

could not find

Let me know if a test case does not work.如果测试用例不起作用,请告诉我。

You can pass eval an f string to do that, but furas' method is much safer/better.您可以通过eval一个 f 字符串来执行此操作,但 furas 的方法更安全/更好。

ABCD = []
KEY = "ABCD"
data = 123
eval(f'{KEY}.append(data)')
print(ABCD)

More on the dangers of eval here更多关于eval的危险在这里

In addition, there are a number of methods for storing and referencing objects without having to put them into a key-value pair relationship (in dict) but furas' method is the most direct and useful for most cases.此外,有许多方法可以存储和引用对象,而不必将它们放入键值对关系(在 dict 中),但 furas 的方法对于大多数情况来说是最直接和最有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM