Python getattr()

In this post, we will see about Python getattr() method.
Python getattr() method returns value of named attribute of the object. If attribute is not present then it returns defaults.


Syntax

As you can see it takes three arguments
object: It is the object whose named attribute value you want to get
name: It is the name of attribute
default(optional): It is the default value getattr will return if it does not find attribute.If you do not specify default and does not find attribute then it will throw AttributeError.
this is simply equal to


Return

It returns the value of the attribute.


Example

Let’s see a very simple example:

class Country: name = 'India' population = 10000 country = Country() print('The Country name is:', getattr(country, "name")) print('Population of india is:', getattr(country, "population")) print('The Country name is:', country.name) print('Population of india is:', country.population)

Output:

The Country name is: India
Population of india is: 10000
The Country name is: India
Population of india is: 10000

Let’s understand about optional paramter default.

class Country: name = 'India' population = 10000 country = Country() print('The Country name is:', getattr(country, "name")) print('Population of india is:', getattr(country, "population")) print('Population of india is:', getattr(country, "capital",'Delhi')) print('Population of india is:', getattr(country, "capital"))

Output:

The Country name is: India
Population of india is: 10000
Population of india is: Delhi
—————————————————————————
AttributeError Traceback (most recent call last)
in ()
7 print(‘Population of india is:’, getattr(country, “population”))
8 print(‘Population of india is:’, getattr(country, “capital”,’Delhi’))
—-> 9 print(‘Population of india is:’, getattr(country, “capital”))

AttributeError: ‘Country’ object has no attribute ‘capital’

As you can see, capital attribute does not exist in the class Country.If we provide default value in getattr, it returns that value. If we do not provide any default and attribute is not present in the class then it throws AttributeError.

That’s all about Python getattr() function.

Leave a Reply

Your email address will not be published. Required fields are marked *