Get a list of class attributes in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Get a list of class attributes in Python #

To get a list of a class's attributes:

  1. Use the dir() function to get a list of the names of the class's attributes.
  2. Use a list comprehension to filter out the attributes that start with a double underscore and the methods.
  3. The list will only contain the class's attributes.
main.py
class Employee(): # 👇️ class variables first = 'one' second = 'two' def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ✅ get list of class attributes class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # 👉️ ['first', 'second'] # ----------------------------------------------------- # ✅ get list of instance attributes result = list(bob.__dict__.keys()) print(result) # 👉️ ['id', 'name', 'salary'] print(bob.__dict__) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100}

The dir function returns a list of the names of the class's attributes, and recursively of the attribute of its base classes.

main.py
class Employee(): # 👇️ class variables first = 'one' second = 'two' def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary # ['__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__', 'first', 'second'] print(dir(Employee)) class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # 👉️ ['first', 'second']

The next step is to filter out all attributes that start with two underscores and all methods.

We used a list comprehension to iterate over the list of names.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The callable function takes an object as an argument and returns True if the object appears callable, otherwise False is returned.

You can use a dict comprehension if you need to get a dictionary of the class variables and the corresponding values.

main.py
class Employee(): first = 'one' second = 'two' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary result = {key: value for key, value in Employee.__dict__.items( ) if not key.startswith('__') and not callable(key)} print(result) # 👉️ {'first': 'one', 'second': 'two'}

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

The __dict__ attribute returns a dictionary containing the object's properties and values.

We had to filter out keys that start with two underscores and methods just like in the previous example.

If you need to get a list of an instance's attributes, use the __dict__ attribute.
main.py
class Employee(): # 👇️ class variables first = 'one' second = 'two' def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) result = list(bob.__dict__.keys()) print(result) # 👉️ ['id', 'name', 'salary'] print(bob.__dict__) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100}

You can use the dict.keys() method to get only the keys of the dictionary.

The dict.keys method returns a new view of the dictionary's keys.

The last step is to use the list() class to convert the view to a list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.