1

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?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
merkle
  • 1,585
  • 4
  • 18
  • 33

2 Answers2

4

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
John
  • 577
  • 4
  • 20
0

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

Wes Doyle
  • 2,199
  • 3
  • 17
  • 32
  • 1
    The selected answer to this question mentions why `getattr` is preferred: https://stackoverflow.com/questions/14084897/getattr-versus-dict-lookup-which-is-faster – Wes Doyle Oct 10 '18 at 17:42