且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

要属性的 Python 字符串

更新时间:2023-02-06 18:01:33

使用内置函数 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.