How to Print Self in Python

Have you ever faced a scenario where your classes are becoming complex to analyze and navigate through, or do you want to check how your class looks at the current state? Python’s built-in features have got you covered.

This tutorial is designed to help you understand and unlock the power of the self in Python. In specific, we’ll take you through how to print self in Python.

What is ‘self’ in Python?

‘Self’ is a convention used in Python to represent the instance of the class. It binds the attributes and methods of a class to its class instance, enabling it to call and modify them. Whatever you can do with ‘self’, you can do with the class instance as well.

How to Print ‘self’ in Python?

To print the ‘self’ in Python, you simply need to call the print function within a method of the class and pass ‘self’ as the argument. This will output the memory location where the Python object for that instance of the class is stored.

Let’s try an example

Create an instance of MyClass and call the method print_self. The output should be the memory location of that particular class instance.

<__main__.MyClass object at 0x000001DEFE3CE050>

In the example output above, ‘0x10a225448’ is the memory address where the object ‘obj’ lives.

Complete code

Conclusion

Using ‘self’ is crucial in Python as it helps in making class definitions cleaner and more manageable. It ensures each class instance has its own namespace. The concept of ‘self’ aligns with the object-oriented programming paradigm (OOP) where data and methods that operate on them are encapsulated within objects.

This tutorial walked you through how to print ‘self’, a fundamental concept in OOP design in Python, and hopefully, you’ve learned something new!