Skip to content

How to print instances of a class using print()? โ€‹

To print instances of a class using the built-in print() function, you can define a __str__ method within the class. The __str__ method should return a string representation of the object, which will be printed when the print() function is called on an instance of the class. Here's an example of a simple class with a __str__ method:

A simple class with a str method in Python

python
class MyClass:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

obj = MyClass(10)
print(obj) # will print "10"

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

In this example, the MyClass class has a single attribute value and a __str__ method that returns the string representation of value. When an instance of MyClass is created and passed to the print() function, the __str__ method is called and its return value is printed.

Note that str is used for user-friendly representation, if you need something more machine-readable, you should use repr method.

Do you find this helpful?

Dual-run preview โ€” compare with live Symfony routes.