0

Is something like this possible?

class MyObject(object):
    attr = 1

def fetch(ob, attr)
    return ob.attr

mo = MyObject()
print fetch(mo, 'attr') #any way to do this?
#expected 1

The reason I ask is because I do know the name of attribute I will be calling, and the object has quite a few attributes and so I could do a massive if/elif block, but that would be ugly and harder to maintain.

emihir0
  • 1,200
  • 3
  • 16
  • 39

1 Answers1

3

It is possible, this is what getattr function does.

def fetch(ob, attr)
    return getattr(ob, attr)

Obviously, you can just use getattr directly.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    Of course, reimplementing `getattr` as `fetch` is rather superfluous… – deceze Oct 04 '16 at 15:02
  • 1
    Of course I'm not going to re-implement it, I will just use `getattr` =). The point was to show an easy to understand example @deceze. – emihir0 Oct 04 '16 at 15:05