Python provides a lot of built-in functions to manipulate objects and their attributes. One such function is "getattr()", which stands for "get attribute". In this article, we will discuss the getattr() function, its usage, and provide examples to illustrate its use.
The getattr() function is a built-in function in Python that returns the value of a named attribute of an object. It takes two arguments - the object whose attribute needs to be retrieved and the name of the attribute. The syntax of the function is as follows:
|
getattr(object, name[, default])
|
The "object" argument is the object whose attribute needs to be retrieved, and the "name" argument is the name of the attribute. The optional "default" argument is the value to be returned if the attribute is not found. If the "default" argument is not provided and the attribute is not found, a "AttributeError" is raised.
Let's take a look at some examples to illustrate the usage of the getattr() function.
Example 1: Retrieving an Attribute
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
name = getattr(person, "name")
print(name)
|
John
Example 2: Retrieving a Non-Existent Attribute
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
gender = getattr(person, "gender", "Unknown")
print(gender)
|
Unknown|
import math
value = getattr(math, "pi")
print(value)
|
In this example, we import the math module and use the getattr() function to retrieve the value of the "pi" attribute of the math module. The output of this code will be:
|
3.141592653589793
|