ExampleEdit & Run
#Use the getattr function

class Example:
    a = 200
    
    def method():
        return "Hello, World!"

print(getattr(Example, "a"))

print(getattr(Example, "method")())
Output:
200Hello, World![Finished in 0.011306002968922257s]

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. 

Syntax:
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.
Parameters:

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.

ExampleEdit & Run
class Student:
    name = 'John'
    age = 20

stu = Student()
print(getattr(stu, 'name'))
print(getattr(stu, 'age'))
Output:
John20[Finished in 0.010842604096978903s]

With a default value 

ExampleEdit & Run
class Example:
   def __init__(self):
      x = 10
      y = 100

e = Example()
print(getattr(e, 'z', 'No such attribute'))
Output:
No such attribute[Finished in 0.011046832893043756s]

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

ExampleEdit & Run
class Greet():
   def greeter(name):
       print(f'Hello, {name}')

getattr(Greet, 'greeter')('Mike')
Output:
Hello, Mike[Finished in 0.010277627035975456s]

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
ExampleEdit & Run
#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__')())
Output:
TrueFalseTruePYTHONPython6[Finished in 0.010415583848953247s]
with lists 
ExampleEdit & Run
#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__')())
Output:
[1, 2, 3, 4, 5, 6][6, 5, 4, 3, 2, 1]15[Finished in 0.009944302961230278s]

With modules

ExampleEdit & Run
import math
import string

print(getattr(math, "sqrt")(16))

print(getattr(string, "ascii_letters"))
Output:
4.0abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ[Finished in 0.017285339068621397s]

Why use getattr Function

  1. 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.

  2. 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.

  3. 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.