0 votes
1 view
in Python by (47.8k 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 (107k 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:-

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...