如何使用Python将字符串转换为类子属性 [英] How to convert string to class sub-attribute with Python
本文介绍了如何使用Python将字符串转换为类子属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以用这样的字符串获取类的属性:
I know I can get a Class's attributes with a string like this:
object.attribute = 'foo'
x = 'attribute'
getattr(object, x)
>>> 'foo'
有没有一种方法可以用字符串更深入"到对象的属性中?换句话说,如果我的对象包含另一个对象,如何使用字符串获取子对象的属性?例如:
Is there a way to "go deeper" into the object's attributes with a string? In other words, if my object contains another object, how can I get the the sub-object's attributes with a string? For example:
object.object.attribute
推荐答案
operator.attrgetter
函数执行以下操作:
class Foo: pass
f = Foo()
f.bar = Foo()
f.bar.baz = Foo()
f.bar.baz.quux = "Found me!"
import operator
print operator.attrgetter("bar.baz.quux")(f) # prints "Found me!"
这篇关于如何使用Python将字符串转换为类子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文