Skip to content

Instantly share code, notes, and snippets.

@akaptur
Created June 25, 2012 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaptur/2990135 to your computer and use it in GitHub Desktop.
Save akaptur/2990135 to your computer and use it in GitHub Desktop.
getattr (snip of Dive into Python)
>>> li = ["Larry", "Curly"]
>>> li.pop (1)
<built−in method pop of list object at 010DF884>
>>> getattr(li, "pop") (2)
<built−in method pop of list object at 010DF884>
>>> getattr(li, "append")("Moe") (3)
>>> li
["Larry", "Curly", "Moe"]
1. This gets a reference to the pop method of the list. Note that this is not
calling the pop method; that would be li.pop(). This is the method itself.
2. This also returns a reference to the pop method, but this time, the method name
is specified as a string argument to the getattr function. getattr is an incredibly
useful built−in function that returns any attribute of any object. In this case, the
object is a list, and the attribute is the pop method.
3. In case it hasn't sunk in just how incredibly useful this is, try this: the
return value of getattr is the method, which you can then call just as if you had
said li.append("Moe") directly. But you didn't call the function directly; you
specified the function name as a string instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment