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.
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)
# >>> 5The 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')) # FalseThe 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.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.