How to Access Object Attributes by String Name in Python
Python's dynamic nature allows you to access an object's attributes using a string representing the attribute's name. This is particularly useful for introspection, dynamic programming, and working with data where attribute names are not known until runtime.
This guide explains how to use getattr()
, hasattr()
, and delattr()
to access, check for, and delete attributes using string names.
Accessing Attributes with getattr()
The getattr()
function is the primary way to access an object's attribute by its string name.
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_name(self):
return self.name
emp1 = Employee('tutorialreference', 100)
print(getattr(emp1, 'name')) # Output: tutorialreference
print(getattr(emp1, 'salary')) # Output: 100
getattr(object, name)
: Retrieves the value of the attribute namedname
from the objectobject
.
Providing a Default Value
getattr()
takes an optional third argument: a default value to return if the attribute doesn't exist. This prevents AttributeError
exceptions.
print(getattr(emp1, 'another', None)) # Output: None (attribute doesn't exist)
- If the attribute 'another' doesn't exist,
getattr()
returnsNone
(or whatever default value you provide).
Accessing Methods
getattr()
can also retrieve methods. You then call the method using parentheses ()
:
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_name(self):
return self.name
emp1 = Employee('tutorialreference', 100)
method = getattr(emp1, 'get_name') # Get the method itself
print(method()) # Output: tutorialreference (call the method)
getattr
is used to return theget_name
method, which is then stored into the variablemethod
and executed.
Checking Attribute Existence with hasattr()
Before accessing an attribute with getattr()
, it's often good practice to check if it exists using hasattr()
:
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_name(self):
return self.name
emp1 = Employee('tutorialreference', 100)
print(hasattr(emp1, 'another')) # Output: False
if hasattr(emp1, 'salary'):
print(getattr(emp1, 'salary')) # Output: 100 (only accessed if it exists)
hasattr()
allows you to check if an attribute exists on a specific object without causing an exception.
Deleting Attributes with delattr()
To delete an attribute using its string name, use delattr()
:
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_name(self):
return self.name
emp1 = Employee('tutorialreference', 100)
delattr(emp1, 'salary') # Delete the 'salary' attribute
print(hasattr(emp1, 'salary')) # Output: False (attribute no longer exists)
- The
delattr()
method is used to delete a specified attribute from a class.