1

The code below

class attsClass():
    def __init__(self,aw,ax,ay,az):
        self.aw = aw
        self.ax = ax
        self.ay = ay
        self.az = az
ac = attsClass('W','X','Y','Z')
ac.ax

here I will get the result which is 'X',but if i call like how i did below we get an error

att_names = ['aw','ax','ay','az']
for att in att_names:
    print(ac.att)

here I can't access the attribute

only with this can I access it

att_names = ['ax','ay','az']
for att in att_names:
    print(att, getattr(ac, att))

can someone explain why?

1 Answer 1

4

Your first example gets the att attribute of ac, which doesn't exist. Variables are not used to resolve attribute names.

When you call getattr, you're passing the variable to a Python function that is able to dynamically read attributes. Since the variable is an argument here, it is resolved.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.