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>Here is the more accurate way, I suppose. (using <code>try-except</code> construction):</p>

<pre><code>...

c = C("required result")
b = B(c)
a = A(b)

def sample(obj, path):
    path_attrs = path.split('.')    # splitting inner attributes path
    inner_attr = None

    for p in path_attrs:
        try:
            inner_attr = getattr(inner_attr if inner_attr else  obj, p)
        except AttributeError:
            print('No %s field' % p)

    print(inner_attr)

sample(a, 'b.c.var')  # will output 'required result'
</code></pre>

python