Python is an object-oriented programming language. In fact, everything in Python is an object (even a class)! Every object has some attributes associated with them. Now, to work well with any object you must know about its attributes.
Hence in this article, we'll discuss objects, attributes, and ways to print these objects' attributes in Python. So, let's get started.
What is an Object in Python?
An object is an instance of a class. It is often regarded as a real-world entity. An object may constitute properties, data (or), and a few methods to operate on that data. It is needed to instantiate a class. Each object has a unique identity.
For instance, consider the human race as a class. So each human will have a name, age, weight, height, and many other properties. Each person can be uniquely identified as an object, (including me, you, your friend, or any other human you know!)
Let's take an example of how to declare an object in Python:
Note that the name and age variables are attributes of the objects of class 'human'.
The above example displays how an object is created (for a user-defined class) and accessed in Python. We have also declared attributes of the object (here, human1 & human2) and accessed them.
Now, we should take a better look at the attributes of an object.
What is an Attribute in Python?
An attribute can be defined as a property of a class or an object. These are data members inside a class (or object) that represents their features. These attributes can be properties (state or value) defining an object or any method acting upon that object.
For instance, let's take our previous example: class human. The name and age variables declared in the class human are actually 'attributes' of 'human'. Along with them, actions (functions) like running, sleeping, reading, walking, and swimming are also attributes of 'human'.
You might get confused between an attribute and an object. The difference between an object and an attribute is that An object is a real-world entity while an attribute is a characteristic of that object.
These attributes are generally defined within a class and shared among all the instances (objects) of that class. An object can be accessed using these attributes.
Attributes are also classified into two types:
- Class Attributes
- Instance (object) Attributes
An Instance attribute is a data member of an object. It is associated with the properties of an object. So, every instance of that class will have the same instance attributes. (It is the purpose of a class, after all!). Their scope of access also lies within the object creation.
For instance, refer to the variables 'name' and 'age' of class 'human'. These are instance variables, allocated to every object separately.
Class Attributes is a data member of the whole class. These attributes share the same memory space and are accessed by all the objects in common.
To learn more about attributes, check our article on static variables in python.
Now that we have learned about objects and attributes, we're all set to learn how to print all attributes of an object in Python.
4 Ways to Print all Attributes of an Object in Python
In order to code efficiently and access an object to obtain its full functionality, one must be aware of all the attributes of the object. Thus, given below are different ways to print all attributes of an object in Python.
01) Using __dir__() method
Python offers an in-built method to print out all attributes of an object (Now, this object may be anything in Python). This method is also known as a magic method or a dunder method in Python.
Let's jump on to an example for better understanding:
Note that the method returns a list with the user-defined attributes given priority.
You'll be surprised to know that, the __dir__() method can also be modified. You can define the __dir__() method in a class to override the default __dir__() method. Let's modify the __dir__() method for the above example:
The s.__dir__() statement calls for the user-defined method which overrides the default dunder method. Notice how different the outputs of the default __dir__() method and the user-defined __dir__() method are.
02) Using dir()
Python offers an in-built function to list out all the attributes of an object. This function returns all attributes (variables, methods, or objects) associated with the passed parameter, in a given scope.
Passing the parameter is optional. If you don't pass a parameter, the dir() function will return all the attributes in the local scope.
Let's take an example:
See! The dir() function returned all the in-built and user-defined attributes in the local scope.
Although the above example had a small list, sometimes the output is long enough to have low readability. To deal with this, Python offers a pprint module.
The "pprint module" is used to print the list in a well-formatted way. Take a look at the example below.
Example: To print the attributes of objects in Python by using the dir() function with an object as an argument.
The pprint() method relates directly to "pretty print"! Take note of how each feature is printed on a separate line. This improves the output's readability.
Now that we've seen some dir() examples, let's go over some key points about the dir() function:
- It returns a list of all the characteristics of an object in the local scope.
- It internally invokes the __dir__() function. Internally, the dir() function implements its functionality via the __dir__() method.
- The dir() function provides an alphabetically sorted output.
Before moving to the next method, let's compare the dir() and __dir__() methods.
Working with dir() function and __dir__() method
a. You already know that the dir() function internally calls for __dir__() method for implementation. Hence, defining the __dir__() method will also change the functionality (and hence output) of the dir() function. Let's take the above example and call the dir() method:
Notice the difference between the outputs returned by dir() function and the __dir__() method. While the __dir__() method provides the defined list as-it-is, the dir() function produces a sorted list of attributes.
b. Now let's take another example of modifying the __dir__() method. You'll be surprised by the output:
The __dir__() method works fine but the dir() function produces a TypeError. You must be wondering WHY!
The code did work for the previous example, didn't it? So why the error? Because the dir() method compares the attributes to produce a sorted list as output. Hence, since the types, string ("alice") and integer (1,2 and rest), cannot be compared with each other, therefore calling dir() method on this produces an error.
Note: The dir() function, in absence of the __dir__() method, calls for the __dict__ attribute to return a list of all the attributes of an object in Python.
03) Using vars() function
Python offers the vars() function which returns a 'dictionary' of all the instance attributes along with their values. It is similar to the above methods, the only difference being, vars() focuses only on instance attributes and also returns their values along with them.
Passing any parameter to the vars() function is optional. It can also be called without passing any parameter to it.
Let's take a few examples to understand the different cases:
a. Without passing any parameter
Note how each attribute is followed by its value.
b. Passing parameter to the vars() function
When the object (here s) is passed as an argument to the vars() method, it produces a dictionary of only the attributes associated with the instance, leaving out the rest of the attributes (as obtained in the above example).
Also, note that the vars() function internally calls for the __dict__ attribute for implementation. The __dict__ attribute is simply a dictionary containing all attributes of that object.
Let's look at the output when we use the __dict__ attribute in the above example:
The output is same! (Hence, remember that the vars() function will produce an error when passed over an object which does not have the __dir__ attribute.)
04) Using inspect module
The inspect module in Python helps in inspecting certain modules or objects that are included in the code. It includes several useful functions that provide information about live objects (like class, function, object, and methods). It can be used to obtain an analysis of objects, for example, to examine a class's content or to display information about an object.
To print all the attributes of an object in Python, you can use the 'getmembers()' function of the inspect module. This function returns the list of tuples containing the attributes along with their values.
Refer to the below image for better readability of the output:
Let's take an example for a better understanding:
I've used pprint module to increase the readability of the output.
Note that this list contains tuples in sorted order. So, the getmembers() function returns a sorted list of all the attributes of an object in Python, along with their respective values.
So far we've discussed different ways to print all attributes of an object in Python. But before moving on to list out all the attributes, you must be able to differentiate between instance attributes and class attributes. So, try and test out these methods along with their variations to understand them better.