...

/

Solution Review: Implement a Print Method

Solution Review: Implement a Print Method

This lesson discusses the __str__ method in Python for the string representation of an object.

We'll cover the following...

Solution:

In Python, and in many other languages for that matter, if we make a class and print an instance of that class the output may vary every time. It prints the address of the object in memory. Consider the following code:

Press + to interact
class Rectangle:
def __init__(self, x1, y1, x2, y2): # class constructor
if x1 < x2 and y1 > y2:
self.x1 = x1 # class variable
self.y1 = y1 # class variable
self.x2 = x2 # class variable
self.y2 = y2 # class variable
else:
print("Incorrect coordinates of the rectangle!")
# test your code
r = Rectangle (2, 7, 8, 4)
print (r)

However, python has a built-in method ...