Python Reference Library →

Python getattr() Function – Access Object Attributes Dynamically

Let’s look at getattr() function – access object attributes dynamically

  1. Notice

    getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
class Box:
    pass
box = Box()
box.value = 3
print(getattr(box, "value"))
print(getattr(box, "missing", "not found"))
Live state

Top-level scope

Box→Object 1
box→Object 2
Object 1 · typeclass BoxObject 2 · BoxBox({'value': 3})
This step

getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

Picture getattr() function – access object attributes dynamically

getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

Image brief

Alt text
A diagram for Python getattr() Function – Access Object Attributes Dynamically. Instructions: class Box: pass box = Box() box.value = 3 print(getattr(box, "value")) print(getattr(box, "missing", "not found")). Displayed result: 3 not found. The final example bindings are Box --> object 1 (type); box --> object 2 (Box). object 1: class Box; object 2: Box({'value': 3})
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python getattr() Function – Access Object Attributes Dynamically". Teaching focus: getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS class Box: pass box = Box() box.value = 3 print(getattr(box, "value")) print(getattr(box, "missing", "not found")) | v DISPLAYED RESULT 3 not found FINAL BINDINGS Box --> object 1 (type) box --> object 2 (Box) object 1: class Box object 2: Box({'value': 3}) Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python getattr() Function – Access Object Attributes Dynamically. Instructions: class Box: pass box = Box() box.value = 3 print(getattr(box, "value")) print(getattr(box, "missing", "not found")). Displayed result: 3 not found. The final example bindings are Box --> object 1 (type); box --> object 2 (Box). object 1: class Box; object 2: Box({'value': 3})

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
class Box:
    pass
box = Box()
box.value = 3
print(getattr(box, "value"))
print(getattr(box, "missing", "not found"))
Live state

Top-level scope

Box→Object 1
box→Object 2
Object 1 · typeclass BoxObject 2 · BoxBox({'value': 3})
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3
not found

What do you expect this program to print?

What does this example display?

class Box:
    pass
box = Box()
box.value = 3
print(getattr(box, "value"))
print(getattr(box, "missing", "not found"))
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3 not found

Follow the printed values in order. The output is: 3 not found

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

More examples and reference

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"))

What to remember

Connect what you noticed in the example with the idea below.

Remember

getattr() retrieves an attribute by its name. A default handles a missing attribute when supplied.

Watch out for this idea

getattr() creates the missing attribute when given a default.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →