gpt4 book ai didi

Python字符串属性

转载 作者:IT老高 更新时间:2023-10-28 21:40:54 28 4
gpt4 key购买 nike

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

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

IE:

如果我这样做 get_foo(obj, "name") 它应该调用 obj.name (将输入视为字符串,但我将其称为 attritube。

谢谢

最佳答案

使用内置函数 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字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253966/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com