Gaurav Tomer
Gaurav Tomer

Reputation: 731

Python - where to exactly use getattr? How is it different from others?

li = ['good', 'bad']

li.pop()
getattr(li, "pop")(1)

Both of above two operations yield the same results than what exactly the difference between them.

As I've read in docs definition of getattr method, it is mentioned that - You can get reference to a function without knowing it's name until runtime.

But here also we take 'pop' name of function. What exactly the difference between them?

Please provide me the true usage?

Upvotes: 0

Views: 355

Answers (3)

Parag Tyagi
Parag Tyagi

Reputation: 8960

Objects in Python can have attributes. For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.

But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called gender_attribute_name.

if

attr_name = 'gender'

then, instead of writing

gender = person.gender

you can write

gender = getattr(person, attr_name)

Some practice:

>>> class Person():
...     name = 'Victor'
...     def say(self, what):
...         print(self.name, what)
... 
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
>>> 

Also getattr() has a 3rd optional parameter which gets sometimes very useful and prevents from silly exceptions. It's like if the attr is not present in the object it'll then return the 3rd parameter as the value (or default value).

Example:

>>> class Person():
...     dob = '04-Aug-1991'
...
>>> getattr(Person, 'dob', '12-Dec-1989')
'04-Aug-1991'
>>> getattr(Person, 'name', 'User')
'User'

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174614

This function comes in handy when the attribue name is coming from another program, from a user input or is not known in advance.

It is also good to check if the attribute exists or not in a given object.

Granted, your use case is a bit trivial, but imagine if you are dealing with some complex class and you are not sure if it has implemented some_method_x, getattr is one way to make sure the attribute exists.

It also has the benefit of being a built-in and like most built-in it works on all objects.

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90859

getattr() is not just for methods, it can also access attributes , Example -

>>> class CA:
...     def __init__(self):
...             self.a = 10
...
>>> c = CA()
>>> getattr(c,'a')
10

Amd getattr() is normal used in such cases, when you do not know the attribute to access, until runtime.

So lets assume if the attribute name is coming in as a string from some file or as user input or some other source, the best way to get the attribute value then would be to use the getattr() method.


For your pop() case , as a very simple example (just for educational purposes , you should not use something like this in real code , as it is dangerous) , lets say you want to take the function you want to run (on l1) as input from user , the way to run that function would be using getattr , Example -

>>> li = ['good', 'bad']
>>> funcToRun = input("Which method :
Which method : pop
>>> getattr(li, funcToRun)()
'bad'

The above is just one example.


Upvotes: 2

Related Questions