Terence Ponce Terence Ponce - 1 month ago 6
Python Question

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

I was reading about the

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 to the subject? When and how do I use this exactly?

Answer

You can view a full example here:

Introspection can be used for different purpose, the one presented in 'Dive Into Python' is simply a way to add functionality (plug-in) dynamically in your application.

By dynamically I mean without doing modification in the core application to add a new feature.

Taking the 'Dive Into Python' example - a simple app to extract attribute from file of different file - you can add the handling of a new file format without doing modification to the original application.

I recommend you finishing the book, everything become increasingly clear during that...

Comments