Fix Python – What is getattr() exactly and how do I use it?

Question

Asked By – Terence Ponce

I’ve recently read about the getattr() function. The problem is that I still can’t grasp the idea of its usage. The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.

I didn’t understand when the book mentioned how you use it to get a reference to a function without knowing its name until run-time. Maybe this is me being a noob in programming, in general. Could anyone shed some light on the subject? When and how do I use this exactly?

Now we will see solution for issue: What is getattr() exactly and how do I use it?


Answer

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

There are only two cases where getattr can be useful.

  • you can’t write object.x, because you don’t know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
  • you want to provide a default value. object.y will raise an AttributeError if there’s no y. But getattr(object, 'y', 5) will return 5.

This question is answered By – blue_note

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0