Python字符串到属性 [英] Python string to attribute
本文介绍了Python字符串到属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何才能实现这样的任务:
How can I achieve such job:
def get_foo(someobject, foostring):
return someobject.foostring
IE:
如果我这样做 get_foo(OBJ,名)
应该叫 obj.name
(见输入作为字符串,但我把它作为一个attritube。
if I do get_foo(obj, "name")
it should be calling obj.name
(see input as string but I call it as an attritube.
感谢
推荐答案
使用内建的功能 GETATTR
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
这篇关于Python字符串到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文