- Get objects methods python
- # Table of Contents
- # Get all methods of a given class in Python
- # Passing an instance of the class to inspect.getmembers()
- # Get all methods of a given class using dir()
- # Getting all methods of an instance with dir()
- Print Methods of Object in Python
- Use dir() to Print All Methods of Python Object
- Filter Magic Methods
Get objects methods python
Last updated: Feb 21, 2023
Reading time · 3 min
# Table of Contents
# 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.
Copied!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__', ), ('get_name', ), ('get_salary', )] 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__', >), ('get_name', >), ('get_salary', >)] 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.
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 .
Copied!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__', >), ('get_name', >), ('get_salary', >)] 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.
Make sure to use inspect.isfunction when passing a class to the inspect.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:
- Use the dir() function to get a list of the names of the class’s attributes.
- Use a list comprehension to filter out the attributes that start with a double underscore and all non-methods.
- The list will only contain the class’s methods.
Copied!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.
Copied!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.
Copied!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.
Copied!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.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Print Methods of Object in Python
Working with Python methods and attributes is very easy but seems challenging when we want to know if a specific object has a particular method/attribute or not.
This tutorial teaches the use of dir() , and inspect.getmembers() to print all methods of a Python object. We will also learn how to filter magic methods and check if an attribute is callable or not.
Finally, we will learn hasattr() and getattr() to find a specific attribute of a Python object and its value.
Use dir() to Print All Methods of Python Object
The dir() is a built-in Python function which returns all the attributes and methods (without values) of a specified object. It not only returns the built-in attributes (also known as properties) and methods but we can also get user-defined properties and methods.
To use the built-in dir() method, let’s create a string-type object and name it first_name which will contain a string-type value. Next, we use the dir() method, pass it first_name object, and save the returned output by the dir() method in a new variable, called result .
Finally, we print the values of result to get a list of all the methods and attributes of a Python object, which is first_name here.
[ ‘__add__’ , ‘__class__’ , ‘__contains__’ , ‘__delattr__’ , ‘__dir__’ , ‘__doc__’ , ‘__eq__’ , ‘__format__’ , ‘__ge__’ , ‘__getattribute__’ , ‘__getitem__’ , ‘__getnewargs__’ , ‘__gt__’ , ‘__hash__’ , ‘__init__’ , ‘__init_subclass__’ , ‘__iter__’ , ‘__le__’ , ‘__len__’ , ‘__lt__’ , ‘__mod__’ , ‘__mul__’ , ‘__ne__’ , ‘__new__’ , ‘__reduce__’ , ‘__reduce_ex__’ , ‘__repr__’ , ‘__rmod__’ , ‘__rmul__’ , ‘__setattr__’ , ‘__sizeof__’ , ‘__str__’ , ‘__subclasshook__’ , ‘capitalize’ , ‘casefold’ , ‘center’ , ‘count’ , ‘encode’ , ‘endswith’ , ‘expandtabs’ , ‘find’ , ‘format’ , ‘format_map’ , ‘index’ , ‘isalnum’ , ‘isalpha’ , ‘isascii’ , ‘isdecimal’ , ‘isdigit’ , ‘isidentifier’ , ‘islower’ , ‘isnumeric’ , ‘isprintable’ , ‘isspace’ , ‘istitle’ , ‘isupper’ , ‘join’ , ‘ljust’ , ‘lower’ , ‘lstrip’ , ‘maketrans’ , ‘partition’ , ‘removeprefix’ , ‘removesuffix’ , ‘replace’ , ‘rfind’ , ‘rindex’ , ‘rjust’ , ‘rpartition’ , ‘rsplit’ , ‘rstrip’ , ‘split’ , ‘splitlines’ , ‘startswith’ , ‘strip’ , ‘swapcase’ , ‘title’ , ‘translate’ , ‘upper’ , ‘zfill’ ]Here, we have retrieved all the attributes and methods, the methods starting and ending with double underscores ( __ ) are called dunder methods or magic methods , which are called by the wrapper functions .
It means dunder or magic methods are not directly invoked by us (the programmers) but their invocation occurs internally from a specific class based on a particular action.
For instance, if we call the dir() method then __dict__() would be invoked behind the scenes. Let’s take another example, where we add two numbers using the + operator, internally, the __add__() method would be called to perform this operation.
As we are not using the magic methods directly so, we can filter them and get a list of methods and attributes that we can directly use from our code. So, let’s dive into the following section to learn how to filter magic methods .
Filter Magic Methods
Here, we use a for loop to iterate over a list returned by dir(first_name) (you can replace first_name with your object) and if statement to filter out magic or dunder methods, we wrap this code with square brackets ( [] ) to get a list type output.