0

I would like to print(use) some attributes of an object instance in the following way. But the code generates an error: AttributeError: 'Obj' object has no attribute 'alphabet'

class Obj(object):
    def __init__(self):
        self.a = 0
        self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print Obj_instance.alphabet
user58925
  • 1,537
  • 5
  • 19
  • 28
  • 3
    Use getattr: https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it#4076099 – fredtantini Dec 04 '17 at 13:51
  • 1
    The accepted answer in the duplicate is pretty poor, IMO. Be sure to read the (currently) [highest-voted answer](https://stackoverflow.com/a/4076099/1126841) instead. – chepner Dec 04 '17 at 14:00
  • Use `getattr` to get a method by a string value, `getattr(Obj_instance, alphabet)` – Manjunath Dec 04 '17 at 14:32

1 Answers1

1

As @fredtantini said use getattr. Here's an example -

class Obj(object):
def __init__(self):
    self.a = 0
    self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print getattr(Obj_instance, alphabet)
RoachLord
  • 993
  • 1
  • 14
  • 28