#Use the getattr function
class Example:
a = 200
def method():
return "Hello, World!"
print(getattr(Example, "a"))
print(getattr(Example, "method")())
The getattr()
function is used to access the value of a specified attribute from an object. It can be used as an alternative to dot notation (i.e. obj.attribute
) to access the attribute of an object.
getattr(obj, name, default = None)
obj |
The object from which to get the attribute value. |
attribute |
The name of the attribute whose value is to be retrieved. |
default |
A default value that will be returned if the attribute does not exist in object. It is optional and defaults to None . |
The function returns the value associated with the specified attribute. If the default
argument is not given and the method does not exist, an AttributeError
will be raised.
class Student:
name = 'John'
age = 20
stu = Student()
print(getattr(stu, 'name'))
print(getattr(stu, 'age'))
With a default value
class Example:
def __init__(self):
x = 10
y = 100
e = Example()
print(getattr(e, 'z', 'No such attribute'))
In the above example, we try to access a non-existent attribute z , but because we had specified a default value, the function returns it instead of raising an AttributeError.
Call a method with getattr() function
class Greet():
def greeter(name):
print(f'Hello, {name}')
getattr(Greet, 'greeter')('Mike')
Since the getattr()
function returns the actual value associated with an attribute, if the value is a method or a function, we can just call it normally. That is we place parenthesis after the returned value with any necessary arguments.
With Builtin data types
with strings
#access string methods
a = 'python'
print(getattr(a, 'islower')())
print(getattr(a, 'isupper')())
print(getattr(a, 'startswith')('p'))
print(getattr(a, 'upper')())
print(getattr(a, 'capitalize')())
print(getattr(a, '__len__')())
with lists
#access list methods
l = [1, 2, 3, 4, 5]
getattr(l, 'append')(6)
print(l)
getattr(l, 'reverse')()
print(l)
print(getattr(l, 'pop')())
print(getattr(l, '__len__')())
With modules
import math
import string
print(getattr(math, "sqrt")(16))
print(getattr(string, "ascii_letters"))
Why use getattr Function
-
Dynamic attribute access: When you need to access attributes dynamically based on user input or other runtime conditions, you can use
getattr()
to fetch the attribute value. This is possible because the getattr() function allows us to accesses an attribute using its name as a string. -
Attribute fallback: If an object has a fallback behavior for missing attributes, you can use
getattr()
to retrieve the attribute value, providing a default value if it doesn't exist. -
Dealing with optional attributes: When working with objects that may or may not have certain attributes, you can use
getattr()
to check for their existence and handle them accordingly.