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 constructorif x1 < x2 and y1 > y2:self.x1 = x1 # class variableself.y1 = y1 # class variableself.x2 = x2 # class variableself.y2 = y2 # class variableelse:print("Incorrect coordinates of the rectangle!")# test your coder = Rectangle (2, 7, 8, 4)print (r)
However, python has a built-in method ...