0

I'm a bit confused about using getattr() with a string. I can do something like

list_ = []
getattr(list_, 'insert')(0,1)

And that will work as expected. When I try to do getattr(list_, 'sort') or getattr(list_, 'pop') then it does not work as expected and will not modify the list. Why do only some string methods work with getattr()?

TheStrangeQuark
  • 2,257
  • 5
  • 31
  • 58
  • 2
    The functions such as `sort` do not take any arguments, but you need to call it: `getattr(list_, 'sort')()`, `getattr(list_, 'pop')()`. – Ajax1234 May 17 '18 at 14:09

1 Answers1

1

You need to call the function that getattr() returns:

>>> a = [2,3,1]
>>> getattr(a, 'sort')()
>>> a
[1, 2, 3]
>>> getattr(a, 'pop')()
3
>>> a
[1, 2]
Zachary Cross
  • 2,298
  • 1
  • 15
  • 22
  • Ahh, I had a misunderstanding of `getattr()`. It returns the function, so without the `()` at the end, I'm returning the function object without actually performing it. Thank you, I understand now. – TheStrangeQuark May 17 '18 at 14:13