attribute lookup str and objects like object.myvar

强颜欢笑 提交于 2019-12-02 23:06:16

问题


I want to know how i can concat object fields with a variable, it's hard to explain to me, let me give an example

Example:

My object have:

myobject.name = 'Red'
myobject.lastname = 'Foo'

and I have a function like this:

my function
..........
some_dumb_field = name

print myobject.some_dumb_field

And this crashes!, how can i concat the str of the field like an object?


回答1:


I'm guessing you are looking for getattr:

print getattr(myobject, some_dumb_field)

This will look up the attribute of myobject whose name is given by the string some_dumb_field.

For example,

getattr(myobject, 'name')

is equivalent to

myobject.name

(Warning: This could be called attribute lookup; you won't find it under the term "concat".)



来源:https://stackoverflow.com/questions/23517521/attribute-lookup-str-and-objects-like-object-myvar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!