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:
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
obj = MyClass(10)
print(obj) # will print "10"
Watch a video course
Python - The Practical Guide
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.