Reputation: 1815
Here is my class implementation
class A:
def __init__(self,a,b):
self.result = None
self.a = a
self.b = b
self.add()
def add(self):
self.result = self.a+self.b
return
My class A has result as an attribute. I want to access the class attribute i.e; result by reading the result string from dictionary. Below is the implementation I tried.
x = 'result' # I will get from other source
obj = A(1,2)
obj.x # Here x = result and the result is the actual class attribute
Error:
AttributeError: A instance has no attribute 'x'
Could anyone tell me how to access the class attributes by converting the string to object?
Upvotes: 1
Views: 1279
Reputation: 2287
As John mentions, getattr
is probably what you are looking for. As an alternative, every object has a __dict__
variable containing key value pairs:
obj = A(1,2)
obj.add()
print(obj.__dict__.get('result'))
You are better off in the general case, however, using getattr
Upvotes: 0
Reputation: 579
Use getattr
getattr
will do exactly what you're asking.
class A:
def __init__(self,a,b):
self.result = ''
self.a = a
self.b = b
self.add()
def add(self):
self.result = self.a+self.b
return
x = 'result' # I will get from other source
obj = A(1,2)
obj.add() #this was missing before thus obj.result would've been 0
print getattr(obj, x) # Here x = result and the result is the actual class attribute
Upvotes: 4