Get all Attributes or Methods of an Object in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
6 min

banner

# Table of Contents

  1. Get all attributes of an Object in Python
  2. Pretty print the object's attributes using pprint()
  3. Get each attribute and its value
  4. Get an object's properties and values using __dict__
  5. Format the object's attributes into a string
  6. Get an object's attributes using vars()
  7. Get all methods of a given class in Python
  8. Passing an instance of the class to inspect.getmembers()
  9. Get all methods of a given class using dir()
  10. Getting all methods of an instance with dir()

# Get all attributes of an Object in Python

Use the dir() function to get all attributes of an object, e.g. print(dir(object)).

The dir function will return a list of the valid attributes of the provided object.

main.py
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ๐Ÿ‘‡๏ธ {'first': 'bobby', 'last': 'hadz', 'age': 30} print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # ๐Ÿ‘‰๏ธ ['first', 'last', 'age'] # ------------------------------- # ['__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__', 'age', 'first', 'last'] print(dir(bobby))

get all attributes of an object

The code for this article is available on GitHub

The dir() function takes an object and returns a list containing the object's attributes.

If you pass a class to the function, it returns a list of the names of the class's attributes, and recursively of the attribute of its base classes.

# Pretty print the object's attributes using pprint()

If you need to pretty print the attributes of the object, use the pprint() method.

main.py
from pprint import pprint class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # ... # ] pprint(dir(bobby))

pretty print object attributes using pprint

The code for this article is available on GitHub

The pprint.pprint() method prints the formatted representation of an object.

# Get each attribute and its value

If you need to get each attribute and its value, use the getattr() function.

main.py
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) for attribute in dir(bobby): print(attribute, getattr(bobby, attribute))
The code for this article is available on GitHub

The getattr() function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn't exist on the object as parameters.

# Get an object's properties and values using __dict__

If you need to get an object's properties and values, use the __dict__ attribute.

main.py
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ๐Ÿ‘‡๏ธ {'first': 'bobby', 'last': 'hadz', 'age': 30} print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # ๐Ÿ‘‰๏ธ ['first', 'last', 'age'] # ------------------------------- values = list(bobby.__dict__.values()) print(values) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 30]

get object properties and values using dict

The code for this article is available on GitHub
The __dict__ attribute returns a dictionary containing the object's properties and values.

You can use the dict.keys() and dict.values() methods if you only need the object's attribute or values.

# Format the object's attributes into a string

If you need to format the object's attributes into a string, use the str.join() method and a formatted string literal.

main.py
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ๐Ÿ‘‡๏ธ dict_items([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(bobby.__dict__.items()) result = ', '.join(f'{key}={str(value)}' for key, value in bobby.__dict__.items()) print(result) # ๐Ÿ‘‰๏ธ first=bobby, last=hadz, age=30

format object attributes into string

The code for this article is available on GitHub

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # ๐Ÿ‘‰๏ธ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

# Get an object's attributes using vars()

Alternatively, you can use vars().

The vars() function returns a dictionary containing the object's properties and values.

main.py
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ๐Ÿ‘‡๏ธ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(vars(bob)) only_attributes = list(vars(bob).keys()) print(only_attributes) # ๐Ÿ‘‰๏ธ ['id', 'name', 'salary'] only_values = list(vars(bob).values()) print(only_values) # ๐Ÿ‘‰๏ธ [1, 'bobbyhadz', 100]

get object attributes using vars

The code for this article is available on GitHub

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.

Which approach you pick is a matter of personal preference. I'd use the __dict__ attribute directly to be more explicit.

# Get all methods of a given class in Python

Use the inspect.getmembers() method to get all methods of a class.

The getmembers() method will return a list containing all of the methods of the class.

main.py
import inspect class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary # โœ… called inspect.getmembers with the class itself list_of_methods = inspect.getmembers(Employee, predicate=inspect.isfunction) # ๐Ÿ‘‡๏ธ [('__init__', <function Employee.__init__ at 0x7f91845bdab0>), ('get_name', <function Employee.get_name at 0x7f9184696e60>), ('get_salary', <function Employee.get_salary at 0x7f9184696ef0>)] print(list_of_methods) # ------------------------------------------------------------------ bob = Employee('Bobbyhadz', 100) # โœ… called inspect.getmembers with instance of the class list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod) # ๐Ÿ‘‡๏ธ [('__init__', <bound method Employee.__init__ of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_name', <bound method Employee.get_name of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_salary', <bound method Employee.get_salary of <__main__.Employee object at 0x7fca7bac09d0>>)] print(list_of_methods)
The code for this article is available on GitHub

We used the inspect.getmembers() method to get a list containing all of the methods of a class.

The inspect.getmembers() method takes an object and returns all the members of the object in a list of tuples.

The first element in each tuple is the name of the member and the second is the value.

We set the predicate argument to inspect.function to get a list containing only the methods of the class.

# Passing an instance of the class to inspect.getmembers()

The inspect.getmembers() method can also be passed an instance of a class, but you have to change the predicate to inspect.ismethod.

main.py
import inspect class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary bob = Employee('Bobbyhadz', 100) list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod) # [('__init__', <bound method Employee.__init__ of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_name', <bound method Employee.get_name of <__main__.Employee object at 0x7fca7bac09d0>>), ('get_salary', <bound method Employee.get_salary of <__main__.Employee object at 0x7fca7bac09d0>>)] print(list_of_methods)

passing instance of class to inspect getmembers

The code for this article is available on GitHub

The inspect.isfunction() predicate returns True if the object is a Python function.

The inspect.ismethod predicate returns True if the object is a bound method written in Python.

Make sure to use inspect.isfunction when passing a class to theinspect.getmembers() method and inspect.ismethod when passing an instance to getmembers().

Alternatively, you can use the dir() function.

# Get all methods of a given class using dir()

This is a three-step process:

  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 all non-methods.
  3. The list will only contain the class's methods.
main.py
class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary class_methods = [method for method in dir(Employee) if not method.startswith('__') and callable(getattr(Employee, method)) ] print(class_methods) # ๐Ÿ‘‰๏ธ ['get_name', 'get_salary']

get all methods of given class using dir

The code for this article is available on GitHub

Filtering out the attributes that start with two underscores is optional.

Make sure to remove the condition if you need to keep method names that start with two underscores.

main.py
class_methods = [method for method in dir(Employee) if callable(getattr(Employee, method)) ] # ['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'get_name', 'get_salary'] print(class_methods)

The class_methods list contains all the method names of the class.

# Getting all methods of an instance with dir()

You can also use this approach to get all methods of an instance.

main.py
class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary bob = Employee('Bobbyhadz', 100) class_methods = [method for method in dir(bob) if not method.startswith('__') and callable(getattr(bob, method)) ] print(class_methods) # ๐Ÿ‘‰๏ธ ['get_name', 'get_salary']

You can use the getattr function if you need to call some of the methods.

main.py
bob = Employee('Bobbyhadz', 100) class_methods = [method for method in dir(bob) if not method.startswith('__') and callable(getattr(bob, method)) ] print(class_methods) # ๐Ÿ‘‰๏ธ ['get_name', 'get_salary'] method_1 = getattr(bob, class_methods[0]) print(method_1()) # ๐Ÿ‘‰๏ธ Bobbyhadz
The code for this article is available on GitHub

The getattr() function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn't exist on the object as parameters.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev