← Go Back

getattr() Built-in Function

getattr() is a built-in function that lets you to get the value of an attribute by giving its name as a string.

class Rectangle:
def __init__(self, b, h):
self.b = b
self.h = h

rect = Rectangle(10, 5)
print("Base:", getattr(rect, "b"))
print("Height:", getattr(rect, "h"))

As seen in the example, getattr(rect, "b") is equivalent to rect.b. The first attribute must be an object; the second, a string containing the name of an attribute of that object.

If the attribute does not exist, the AttributeError exception is thrown, unless a default value is given as the third argument.

# 50 is the default value.
print("Area:", getattr(rect, "area", 50))

built-ins oop

🐍 You might also find interesting: