Project Brief
Yesterday, we coded a Rectangle class that had a width and a height attribute. The class also had an area(), perimeter(), and an is_square() method.
Your task for today is to add two magic methods to that class __str__ and __eq__. The __str__ method should return a string representation of the Rectangle and __eq__ should enable comparing two different rectangle instances returning True or False based on whether the rectangles are similar or not (i.e., have the same width and height).
Expected Output
Your task is to simply define the class. You don’t need to call the class.
Environment Setup Instructions
You don’t need to install any libraries.
Resources
Magic methods in Python, also known as dunder methods, are special methods that start and end with double underscores (e.g., __init__
, __str__
). They allow you to define the behavior of objects for built-in operations like creation, representation, comparison, and arithmetic. Essentially, they enable you to customize how your objects interact with Python's syntax and built-in functions. For example, __str__
defines how an object is converted to a string, and __eq__
defines how two objects are compared for equality.
Here's a short example of a Vector
class with the __add__
magic method to illustrate how magic methods work:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented
def __str__(self):
return f"Vector({self.x}, {self.y})"
# Example usage:
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3) # Output: Vector(6, 8)
__add__
: Defines how to add twoVector
objects using the+
operator.__str__
: Defines the string representation of theVector
object.
In this example, adding two Vector
objects using +
results in a new Vector
object with combined x and y components. The __str__
method allows for a readable string output when printing a Vector
object.
Project Solution
Feel free to post your questions or comments in the comment section below.
Happy Coding!
Daily Python Projects Team