Last updated: Apr 10, 2024
Reading timeยท6 min
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.
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))
The dir() function takes an object and returns a list containing the object's attributes.
pprint()
If you need to pretty print the attributes of the object, use the pprint()
method.
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))
The pprint.pprint() method prints the formatted representation of an object.
If you need to get each attribute and its value, use the getattr()
function.
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 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.
__dict__
If you need to get an object's properties and values, use the __dict__
attribute.
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]
__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.
If you need to format the object's attributes into a string, use the
str.join()
method and a
formatted string literal.
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
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
.
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # ๐๏ธ bobbyhadz
Make sure to wrap expressions in curly braces - {expression}
.
Alternatively, you can use vars()
.
The vars()
function returns a dictionary containing the object's properties
and values.
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]
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.
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.
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)
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.
predicate
argument to inspect.function
to get a list containing only the methods of the class.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
.
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)
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.
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.
This is a three-step process:
dir()
function to get a list of the names of the class's
attributes.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']
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.
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.
You can also use this approach to get all methods of an instance.
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.
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 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.
You can learn more about the related topics by checking out the following tutorials: