Python built-in Method - getattr()
The getattr()
method in Python is a built-in function that returns the value of a named attribute of an object.
The syntax for getattr()
is as follows:
getattr(object, name[, default])
Here, object
is the object whose attribute is to be accessed, name
is a string representing the name of the attribute, and default
is an optional value that is returned if the named attribute is not found.
For example:
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("John", 30) name = getattr(person, "name") print(name) # Output: John salary = getattr(person, "salary", 10000) print(salary) # Output: 10000
In the example above, we define a Person
class with two attributes name
and age
. We create an instance of the class called person
. We use getattr()
to retrieve the value of the name
attribute of person
and store it in a variable called name
. We then print the value of name
, which is "John".
We also use getattr()
to try to retrieve the value of an attribute called salary
of person
. Since person
does not have a salary
attribute, we provide a default value of 10000 which is returned.
getattr()
is useful when you want to access an attribute dynamically, based on a string representing the attribute name. This can be especially useful when working with objects whose attributes are not known ahead of time or are generated at runtime.