Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I was reading 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?

1 Answer

0 votes
by (106k points)

The 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 attributes 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.

To know more about this you can have a look at the following video tutorial:-

Browse Categories

...