pythonfunctionbuilt-ingetattrclass-attributes

What is & How to use getattr() in Python?


I read an article about the getattr function, but I still can't understand what it's for.

The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.

When and how do I use this exactly? The book said something about using it to get a reference to a function whose name isn't known until runtime, but when and why would I use this?


Solution

  • getattr(object, 'x') is completely equivalent to object.x.

    There are only two cases where getattr can be useful.