Fundamentals 5 min read

Using Python's setattr(), hasattr(), and getattr() Functions

This article explains how Python's built‑in functions setattr(), hasattr() and getattr() can be used to set, check, and retrieve object attributes, including syntax, parameters, return values, and practical code examples demonstrating each operation.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python's setattr(), hasattr(), and getattr() Functions

The setattr() function sets the value of an existing attribute on an object. Its syntax is setattr(object, name, value) , where object is the target, name is the attribute name as a string, and value is the new value. It returns nothing.

Example:

class A(object):
    bar = 1

a = A()
print(1, getattr(a, 'bar'))  # get attribute 'bar'
# >>> 1
setattr(a, 'bar', 5)          # set attribute 'bar' to 5
print(a.bar)
# >>> 5

The hasattr() function checks whether an object possesses a given attribute, returning True or False . Syntax: hasattr(object, name) .

Example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate()
print(hasattr(point1, 'x'))   # True
print(hasattr(point1, 'y'))   # True
print(hasattr(point1, 'z'))   # True
print(hasattr(point1, 'no'))  # False

The getattr() function retrieves the value of an attribute, optionally providing a default if the attribute does not exist. Syntax: getattr(object, name[, default]) . If the attribute is missing and no default is supplied, an AttributeError is raised.

Example:

class A(object):
    bar = 1

a = A()
print(getattr(a, 'bar'))          # >>> 1
print(getattr(a, 'bar2'))         # raises AttributeError
print(getattr(a, 'bar2', 3))      # >>> 3 (default value)

Additional notes: setattr() can also create a new attribute if it does not already exist. hasattr() requires the attribute name as a string, and getattr() can be used to obtain methods, returning the method object or its memory address.

reflectionobject-orientedgetattrhasattrsetattr
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.