Python string to attribute(Python字符串属性)
问题描述
我怎样才能完成这样的工作:
How can I achieve such job:
def get_foo(someobject, foostring):
return someobject.foostring
IE:
如果我这样做 get_foo(obj, "name")
它应该调用 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
.
Use the builtin function getattr
.
getattr(object, name[, default])
返回object的命名属性的值.name 必须是字符串.如果字符串是对象属性之一的名称,则结果是该属性的值.例如,getattr(x, 'foobar')
等价于 x.foobar
.如果命名属性不存在,则返回default,否则返回AttributeError 被引发.
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar')
is equivalent to x.foobar
. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
这篇关于Python字符串属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python字符串属性


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01