|
|
|
|
|
by walrus
4985 days ago
|
|
Short answer: not really. Long answer: In [1]: from operator import attrgetter
In [2]: class Person:
...: def __init__(self, name):
...: self.name = name
...:
In [3]: me = Person('walrus')
In [4]: getattr(me, 'name')
Out[4]: 'walrus'
In [5]: attrgetter('name')(me)
Out[5]: 'walrus'
This is potentially useful if you're using `map`: In [6]: people = [me, Person('aschwo')]
In [7]: list(map(lambda obj: getattr(obj, 'name'), people))
Out[7]: ['walrus', 'aschwo']
In [8]: list(map(attrgetter('name'), people))
Out[8]: ['walrus', 'aschwo']
Really, though, the functional programming idioms don't meld too well with Python. I think this is a lot nicer: In [9]: [person.name for person in people]
Out[9]: ['walrus', 'aschwo']
|
|
PS: map returns a list, no need to call list() on it.