属性查找str和诸如object.myvar之类的对象 [英] attribute lookup str and objects like object.myvar

查看:53
本文介绍了属性查找str和诸如object.myvar之类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用变量连接对象字段,很难向我解释,让我举个例子

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

示例:

我的对象有:

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

我有一个像这样的函数:

and I have a function like this:

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

print myobject.some_dumb_field

这崩溃了,我如何像对象一样连接字段的str?

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

推荐答案

我猜您正在寻找 getattr

print getattr(myobject, some_dumb_field)

这将查找 myobject 其名称由字符串 some_dumb_field 给出。

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

例如,

getattr(myobject, 'name')

等价于

myobject.name

(警告:这可以称为属性查找;您将无法在 concat一词下找到它。)

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

这篇关于属性查找str和诸如object.myvar之类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆