In this tutorial we will learn about python getattr() method and its uses.
What is python getattr() method?
Python getattr() method is used to access the values of attributes of python objects. If a specified object has no attributes, it will return the default value provided to the method.
The syntax of python getattr() is:
Python getattr() method Parameters
The getattr() method takes 3 parameters:
- object – Name of the object whose attributes value want to be accessed.
- name – normal string that contains the name of an attribute.
- default (optional) – Default value which will be returned when given attributes is not found.
getattr() is also equivalent to:
Both getattr() and “object.name” will do the same thing.
Let’s check an example of the getattr() method.
Example 1: How to use the getattr() method on the python class?
When we run the above program we will get following output:
Example 2: Accessing attributes that are not declared.
The output will be as follow:
As you can see we are accessing attributes that are not present in the object, and it throws an error as “object has no attribute” if in the above program we use default parameter, it will not raise any error.
We can do the same thing by calling the class with the attribute name.
Example 3: Accessing object value without getatt() method.
below is the output:
Rules of getattr() method
- It will only return the value of the attribute if it is found.
- If the attribute is not present and the default value is not given AttributeError exception will occur.
- It will return default if no named attribute is found.