2

I am thinking is there any way to replace a object.variable with value in place for class object.

For example:

class A:
    def __init__(self,a):
        self.attr1 = a

a_obj1 = A('Name1')
print(a_obj1.attr1)

Prints Name1

And if I keep the attr1 in a variable, and try to access it, then it

a_obj2 = A('Name2')
attrName = 'attr1'
print(a_obj2.attrName)

Shows AttributeError: 'A' object has no attribute 'attrName'

My understanding is that the REPL parser of python probably not expanding any thing after . which makes sense. But is there any way to achieve this? In particular combine a varaible's value with another variable to make a variable?

Update: Thanks chris . Found the solution.

1
  • 2
    You need getattr: try getattr(a_obj2, attrName) Commented Dec 31, 2019 at 4:15

2 Answers 2

1

try it

class A:
    def __init__(self,a):
        self.attr1 = a

a_obj1 = A('Name1')
print(a_obj1.attr1)
a_obj2 = A('Name2')
attrName = 'attr1'
print(getattr(a_obj2, attrName))
Sign up to request clarification or add additional context in comments.

Comments

1

Use getattr() with the format gettattr(a_obj, attrName)

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.