In order to print the instances of a class using the print() function, you can override the __str__() method in your class. The __str__() method allows you to define a string representation of your object.
Here's an example:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"MyClass instance - name: {self.name}, age: {self.age}"
# Create instances of MyClass
obj1 = MyClass("John", 25)
obj2 = MyClass("Alice", 30)
# Print the instances using the print() function
print(obj1)
print(obj2)
Output:
MyClass instance - name: John, age: 25
MyClass instance - name: Alice, age: 30
In the above example, the __str__() method is overridden in the MyClass class. It returns a string that represents the object in a customized format. When you call print(obj1) or print(obj2), the __str__() method of the corresponding instance is invoked, and the returned string is printed using the print() function.