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
解决方案
The operator.attrgetter function does this:
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!"