Table of Contents
💡 TL;DR
To get all methods of object, use inbuilt
dir()
method
12345678910111213 str = "java2blog"## Print methods and attributes of objectresult = dir(str)print(result)## Print only methods of objectsmethodList = [attribute for attribute in dir(str)if callable(getattr(str, attribute))and attribute.startswith('__') is False]print(methodList)
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.
Example Code:
1 2 3 4 5 |
first_name = "Mehvish" result = dir(first_name) print(result) |
OUTPUT:
1 2 3 |
['__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.
Example Code:
1 2 3 4 5 |
list_of_method = [methods for methods in dir(first_name) if methods.startswith('__') is False] print(list_of_method) |
OUTPUT:
1 2 3 |
['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'] |
Now, we have all those attributes and functions that we can use directly from our code. For instance, we can use upper
and count
with ()
as follows:
1 2 3 4 |
print(first_name.upper()) #converts to upper case print(first_name.count('h')) #counts the occurrence of a specific characters |
OUTPUT:
1 2 3 4 |
MEHVISH 2 |
One worth noting point is, how we know whether we have to write ()
or not because we have filtered magic methods
only and still have some attributes that might not be callable. For that, we can use callable()
and pass it to the object that we want to check.
Use callable()
to Check if an Object is Callable or Not
If callable()
returns True
then, the specified object is callable and we can use ()
with it. On the other hand, if callable()
returns False
then, the specified object is not callable and we don’t need to use ()
.
In simple words, we can say that ()
are used with methods/functions, not with attributes/properties. See the following code to understand it.
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 |
def display_first_name(): return "Mehvish" # created an object of display_first_name() first_name_object = display_first_name print(callable(first_name_object)) # create one test variable last_name = "Ashiq" print(callable(last_name)) |
OUTPUT:
1 2 3 4 |
True False |
The above output shows that we can use ()
with first_name_object
only. Let’s test it by using the following print
statements.
1 2 3 4 |
print(first_name_object()) #OUTPUT: Mehvish print(last_name()) #OUTPUT: TypeError: 'str' object is not callable |
The first print
statement returns the desired value Mehvish
which proves that the first_name_object
is callable and allows us to use ()
while the second print
statement generates TypeError
saying that it is not callable so, we can’t use ()
.
It means we can only use ()
with functions/methods, not with attributes/properties. So, there might be a chance that we also want to filter attributes/properties. Let’s explore it in the following section.
Filter All Attributes/Properties that Are Not Callable
Let’s create a Person
class to learn how to filter all attributes/properties that are not callable. This Person
class has four attributes and a method which are briefly explained below:
first_name
– This attribute contains the first name of a person.last_name
– This attribute contains the last name of a person.age
– This attribute contains the age of a person.call_display_information
– This attribute holds a reference to a method which is defined asdisplay_information()
.display_information()
– This method returns a list offirst_name
,last_name
, andage
of a person.
Example Code:
1 2 3 4 5 6 7 8 9 10 |
class Person: first_name = "Mehvish" last_name = "Ashiq" age = "35" def display_information(): return [first_name, last_name, age] call_display_information = display_information |
Now, use the following code to filter all attributes which are not callable and magic
or dunder
methods as we will not be using them.
1 2 3 4 5 6 7 8 |
## Create object of Person class person = Person methodList = [attribute for attribute in dir(person) if callable(getattr(person, attribute)) and attribute.startswith('__') is False] print(methodList) |
OUTPUT:
1 2 3 |
['call_display_information', 'display_information'] |
See, we only get the methods of the objects which we are looking for.
Note: The
dir()
method can be used on any type of Python object, it can be of string type, integer type, or user-defined type (for example,Student
).
Use the inspect
Module to Print All Methods of Python Object
The inspect
module has various useful functions but we are focused on getmembers()
, it returns all members of a specified object as a list containing (name, value)
pairs, which are sorted by name.
Example Code:
1 2 3 4 5 6 |
import inspect first_name = "Mehvish" result = inspect.getmembers(first_name) print(result) |
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 |
[('__add__', <method-wrapper '__add__' of str object at 0x00000202EFA7FF70>), ('__class__', <class 'str'>), ('__contains__', <method-wrapper '__contains__' of str object at 0x00000202EFA7FF70>), ('__delattr__', <method-wrapper '__delattr__' of str object at 0x00000202EFA7FF70>), ... ... ... ('translate', <built-in method translate of str object at 0x00000202EFA7FF70>), ('upper', <built-in method upper of str object at 0x00000202EFA7FF70>), ('zfill', <built-in method zfill of str object at 0x00000202EFA7FF70>)] |
Here, we have used ...
to make the above output more readable but you’ll have multiple (name, value)
pairs. We can also filter magic methods
and check if an object is callable or not as we did while using the dir()
method.
Till this point, we have learned how to list all methods/attributes of a Python object but what if we want to know about a specific attribute or a method?
For example, we have a class Student
and we want to check if the Student
class has a first_name
attribute or a display_information()
method. Let’s dive into the following section to learn it in detail.
Use getattr()
& hasattr()
to Print a Specific Method of a Python Object
Let’s create a Student
class to use the getattr()
and hasattr()
methods. The following Student
class has three attributes (first_name
, last_name
, and age
) and a method (display_information()
).
Example Code:
1 2 3 4 5 6 7 8 9 |
class Student: first_name = "Mehvish" last_name = "Ashiq" age = "35" def display_information(): return [first_name, last_name, age] |
Next, create an object of the Student
class as follows:
1 2 3 |
student = Student |
Now, we can use the hasattr()
method to check if the student
object has the specified attributes/methods.
To use hasattr()
, we pass the object name and property name as the first parameter and second parameter respectively. See the following code fence:
1 2 3 4 5 6 7 |
print("Has 'first_name' attribute? ", hasattr(student, "first_name")) print("Has 'last_name' attribute? ", hasattr(student, "last_name")) print("Has 'age' attribute? ", hasattr(student, "age")) print("Has the 'display_information' method? ", hasattr(student, "display_information")) print("Has 'section' attribute? ", hasattr(student, "section")) |
OUTPUT:
1 2 3 4 5 6 7 |
Has 'first_name' attribute? True Has 'last_name' attribute? True Has 'age' attribute? True Has the 'display_information' method? True Has 'section' attribute? False |
The hasattr()
returns True
if an object has the specified attribute or method; otherwise, False
.
We can also use the getattr()
method similarly but it returns the value of the specified attribute or method as follows. Note that, we will get an AttributeError
error if we will try to get the value of an attribute which is not defined.
1 2 3 4 5 6 |
print("Value of 'first_name' attribute? ", getattr(student, "first_name")) print("Value of 'last_name' attribute? ", getattr(student, "last_name")) print("Value of 'age' attribute? ", getattr(student, "age")) print("Value of 'display_information' method? ", getattr(student, "display_information")) |
OUTPUT:
1 2 3 4 5 6 |
Value of 'first_name' attribute? Mehvish Value of 'last_name' attribute? Ashiq Value of 'age' attribute? 35 Value of 'display_information' method? <function Student.display_information at 0x00000202F2A3F760> |
Note that, we can use the type(object_name)
and id(object_name)
methods to get the data type and unique id of the specified object, don’t forget to replace object_name
with your object_name
.