在 python 中,是否可以获取变量值,其中变量名作为函数参数传递
In python, is it possible to fetch variable value, where the variable name is passed as a function argument
我试图通过将变量名传递给调用函数来获取变量值。
我的目的是根据作为参数传递的变量名获取变量值。
class myConfigConstants():
Name = "XYZ"
Address = "abcd"
Age = 10
def __init__(self):
self.value = ""
def fetch_myConfigConstants(self, strVariableName: str):
self.value = myConfigConstants.strVariableName
print(self.value)
return self.value
mc = myConfigConstants()
mc.fetch_myConfigConstants('Name')
预期输出:
XYZ
这导致错误:
AttributeError: 类型对象 'myConfigConstants' 没有属性 'strVariableName'
我知道它正在寻找确切的属性,但是如何使传递的参数名称在运行时解析为实际属性。
您可以使用getattr
函数。
getattr(self, strVariableName)
在您的代码中,
...
def fetch_myConfigConstants(self, strVariableName: str):
self.value = getattr(self, strVariableName)
print(self.value)
return self.value
希望对您有所帮助。
您可以使用 getattr
来实现。
self.value = getattr(myConfigConstants, strVariableName)
我试图通过将变量名传递给调用函数来获取变量值。 我的目的是根据作为参数传递的变量名获取变量值。
class myConfigConstants():
Name = "XYZ"
Address = "abcd"
Age = 10
def __init__(self):
self.value = ""
def fetch_myConfigConstants(self, strVariableName: str):
self.value = myConfigConstants.strVariableName
print(self.value)
return self.value
mc = myConfigConstants()
mc.fetch_myConfigConstants('Name')
预期输出: XYZ
这导致错误: AttributeError: 类型对象 'myConfigConstants' 没有属性 'strVariableName'
我知道它正在寻找确切的属性,但是如何使传递的参数名称在运行时解析为实际属性。
您可以使用getattr
函数。
getattr(self, strVariableName)
在您的代码中,
...
def fetch_myConfigConstants(self, strVariableName: str):
self.value = getattr(self, strVariableName)
print(self.value)
return self.value
希望对您有所帮助。
您可以使用 getattr
来实现。
self.value = getattr(myConfigConstants, strVariableName)