Python,将变量值评估为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/632856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, Evaluate a Variable value as a Variable
提问by Antonius Common
I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?
我想做如下操作:特别是“f.eval(field)”部分,这样它将变量的值作为字段名称进行评估。如何在 Python 中实现这一目标?
def punctuated_object_list(objects, field):
field_list = [f.eval(field) for f in objects]
if len(field_list) > 0:
if len(field_list) == 1:
return field_list[0]
else:
return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
else:
return u''
回答by Devin Jeanpierre
getattr(f, field)
, if I understand you correctly (that is, if you might have field = "foo"
, and want f.foo
). If not, you might want to clarify. Python has an eval()
, and I don't know what other languages' eval()
you want the equivalent of.
getattr(f, field)
,如果我理解正确(也就是说,如果您可能拥有field = "foo"
,并且想要f.foo
)。如果没有,您可能想澄清一下。Python 有一个eval()
,我不知道eval()
你想要什么其他语言。
回答by hasen
getattr( object, 'field' ) #note that field is a string
f = 'field_name'
#...
getattr( object, f )
#to get a list of fields in an object, you can use dir()
dir( object )
For more details, see: http://www.diveintopython.org/power_of_introspection/index.html
有关更多详细信息,请参阅:http: //www.diveintopython.org/power_of_introspection/index.html
Don't use eval, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code.
不要使用 eval,即使在这种特殊情况下字符串是安全的!只是不要让自己习惯它。如果您从用户那里获取字符串,则它可能是恶意代码。
Murphy's law: if things can go wrong, they will.
墨菲定律:如果事情可能出错,他们就会出错。
回答by MarkusQ
The python equivalent of eval()
is eval()
python的等价物eval()
是eval()
x = 9
eval("x*2")
will give you 18.
会给你18。
v = "x"
eval(v+"*2")
works too.
也有效。
回答by Soviut
To get at a list of all the fields in a Python object you can access its __dict__
property.
要获取 Python 对象中所有字段的列表,您可以访问其__dict__
属性。
class Testing():
def __init__(self):
self.name = "Joe"
self.age = 30
test = Testing()
print test.__dict__
results:
结果:
{'age': 30, 'name': 'Joe'}