Last updated: Apr 10, 2024
Reading timeยท4 min
To iterate over an object's attributes:
__dict__
attribute to get a dictionary containing the object's
properties and values.dict.items()
method to get a view of the dictionary's items.for
loop to iterate over the object's attributes.class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in emp1.__dict__.items(): # name bobbyhadz # salary 100 print(attribute, value)
The example uses the __dict__
attribute to get a dictionary containing the
object's properties and values.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) # ๐๏ธ {'name': 'bobbyhadz', 'salary': 100} print(emp1.__dict__)
We can use the dict.items()
method to get a view object we can iterate over.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in emp1.__dict__.items(): # name bobbyhadz # salary 100 print(attribute, value)
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
The last step is to use a for loop to iterate over the object's attributes.
An alternative to using the __dict__
attribute is to use the built-in vars()
function.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in vars(emp1).items(): # name bobbyhadz # salary 100 print(attribute, value)
The vars function takes
an object and returns the __dict__
attribute of the given module, class,
instance or any other object that has a __dict__
attribute.
The vars()
function raises a TypeError
if the provided object doesn't have a
__dict__
attribute.
If you need to include the class variables when iterating, use the dir()
function.
This is a three-step process:
dir()
function to get a list of the names of the object's
attributes.for
loop to iterate over the object's attributes.class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute in dir(emp1): print(attribute, getattr(emp1, attribute)) result = [attribute for attribute in dir(emp1) if not attribute.startswith('__')] print(result) # ๐๏ธ ['cls_id', 'name', 'salary']
The dir() function returns a list of the names of the object's attributes, and recursively of the attribute of its base classes.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cls_id', 'name', 'salary'] print(dir(emp1))
You can also pass a class to the dir()
function, it doesn't just accept
instances.
If you need to exclude the attributes that start with two underscores, use a list comprehension.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) attributes = [attribute for attribute in dir(emp1) if not attribute.startswith('__')] print(attributes) # ๐๏ธ ['cls_id', 'name', 'salary'] for attr in attributes: # cls_id employee # name bobbyhadz # salary 100 print(attr, getattr(emp1, attr))
getattr()
function if you need to get the value of an attribute when given the attributes name as a string.The getattr() function returns the value of the provided attribute of the object.
The function takes the following parameters:
Name | Description |
---|---|
object | the object whose attribute should be retrieved |
name | the name of the attribute |
default | a default value for when the attribute doesn't exist on the object |
If your class has methods, you might also want to exclude the methods when iterating over the object's attributes.
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name emp1 = Employee('bobbyhadz', 100) attributes = [attribute for attribute in dir(emp1) if not attribute.startswith('__') and not callable(getattr(emp1, attribute))] print(attributes) # ๐๏ธ ['cls_id', 'name', 'salary'] for attr in attributes: # cls_id employee # name bobbyhadz # salary 100 print(attr, getattr(emp1, attr))
The callable function takes an
object as an argument and returns True
if the object appears callable,
otherwise False
is returned.
We used the function to exclude all methods from the attributes.
If you only want to iterate over the class's variables, you will pass the class
to the dir()
function, not the instance.
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, name, salary): self.name = name self.salary = salary class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # ๐๏ธ ['another', 'cls_id'] for attr in class_variables: # another foo # cls_id employee print(attr, getattr(Employee, attr))
We passed the class to the dir()
function and filtered out all class variables
that start with two underscores and all class methods before iterating.
You can learn more about the related topics by checking out the following tutorials: