要属性的 Python 字符串 [英] Python string to attribute

查看:27
本文介绍了要属性的 Python 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能完成这样的工作:

def get_foo(someobject, foostring):返回 someobject.foostring

浏览器:

如果我执行 get_foo(obj, "name") 它应该调用 obj.name(将输入视为字符串,但我将其称为属性.>

谢谢

解决方案

使用内置函数 getattr.

<块引用>

getattr(object, name[, default])

返回对象的命名属性的值.name 必须是字符串.如果字符串是对象属性之一的名称,则结果是该属性的值.例如,getattr(x, 'foobar') 等价于 x.foobar.如果指定的属性不存在,则返回 default(如果提供),否则返回 AttributeError 被引发.

How can I achieve such job:

def get_foo(someobject, foostring):
    return someobject.foostring

IE:

if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.

Thanks

解决方案

Use the builtin function getattr.

getattr(object, name[, default])

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 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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