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
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?
getattr(object, 'x') is completely equivalent to
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.ywill raise an
AttributeErrorif there’s no
getattr(object, 'y', 5)will return