How to access a object's attrbute by using string corresponding to name if object is attribute of some other object
<p>I have 3 classes as below:- </p>

<pre><code>class C(object):
    def __init__(self, v):
        self.var = v

class B(object):
    def __init__(self, c):
        self.c = c

class A(object):
    def __init__(self, b):
        self.b = b

I have created instances as 
c = C("required result")
b = B(c)
a = A(b)

&gt;&gt;&gt; a.b.c.var
'required result'
</code></pre>

<p>Now I need to pass b.c.var as a string to some function and get the value of var similar to sample function as below - </p>

<pre><code>`sample(a, 'b.c.var')` should return 'required result'`
</code></pre>

<p>What should be pythonic way to achieve this
This is my attempt :- </p>

<pre><code>for attr in ('b', 'c', 'var'):
    a = getattr(a, attr)
&gt;&gt;&gt; print a
required result
</code></pre>

<p>You can use <a href="https://docs.python.org/3/library/operator.html#operator.attrgetter" rel="nofollow">operator.attrgetter</a> which takes a dotted name notation, eg:</p>

<pre><code>from operator import attrgetter
attrgetter('b.c.var')(a)
# 'required result'
</code></pre>

<p>Then if you don't like that syntax, use it to make your <code>sample</code> function, eg:</p>

<pre><code>def sample(obj, attribute):
    getter = attrgetter(attribute)
    return getter(obj)
</code></pre>

<p>From the documentation linked above, the <code>operator.attrgetter</code> uses the equivalent of the following code:</p>

<pre><code>def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj
</code></pre>

<p>So in fact - your original code was just trying to do the equivalent of <code>resolve_attr</code>...</p>

python