Yandex

Python getattr() Function – Access Object Attributes Dynamically



Python getattr() Function

The getattr() function in Python is used to get the value of an attribute of an object dynamically. It's especially useful when the attribute name is stored as a string or determined at runtime.

Syntax

getattr(object, name[, default])

Parameters:

  • object – The object whose attribute you want to access.
  • name – A string representing the attribute name.
  • default (optional) – A value to return if the attribute does not exist.

Returns:

  • The value of the specified attribute if it exists.
  • If the attribute doesn't exist and default is provided, it returns default.
  • If the attribute doesn't exist and no default is given, it raises an AttributeError.

Example: Basic Usage of getattr()

class Person:
    name = "Alice"
    age = 30

p = Person()
print(getattr(p, 'name'))
Alice

Why? Because 'name' is an attribute of object p.

Example: Using default Value

print(getattr(p, 'gender', 'Not Specified'))
Not Specified

This avoids an error and returns a default string if the attribute does not exist.

Use Case: Dynamic Attribute Access

attr_name = input("Enter attribute (name or age): ")
print(getattr(p, attr_name, "Attribute not found"))

Why is this useful?

  • When building flexible code like dynamic APIs
  • When attributes are not known ahead of time
  • For reflective operations and serialization

Common Mistakes

  • Passing a non-string as name will raise a TypeError
  • Not providing default can lead to AttributeError if attribute doesn’t exist

Interview Tip

getattr() is often used in interview questions that involve object introspection or building generic class utilities.

Summary

  • getattr() fetches an attribute from an object by name
  • Returns the attribute value if it exists
  • Returns default or raises error if the attribute is missing

Practice Problem

Create a class Car with attributes brand and year. Write a program that asks the user to enter an attribute name and prints the value using getattr(). If the attribute doesn’t exist, print "Unknown attribute".

class Car:
    brand = "Toyota"
    year = 2022

c = Car()
attr = input("Enter attribute (brand/year): ")
print(getattr(c, attr, "Unknown attribute"))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M