Write a Rectangle class.
Rectangle(width, height)
__init__(self, width, height) — stores both as attributes.area(self) — returns width * height.perimeter(self) — returns 2 * (width + height).__str__(self) — returns "WIDTHxHEIGHT", e.g. "4x5" for a 4-by-5 rectangle. This is called automatically by str(rect) and print(rect).r = Rectangle(4, 5)
r.area() // → 20
r.perimeter() // → 18
str(r) // → "4x5"
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def __str__(self):
return f"{self.width}x{self.height}"
area and perimeter are the same formulas from Rectangle Area back in the basics section — the only difference is they now read self.width/self.height (the object's own stored attributes) instead of taking width/height as parameters directly. That's the core shift this section is about: instead of passing the same values into every function that needs them, you store them once on the object, and every method reaches for self.whatever to get at them.
__str__ is the dunder method from the lesson — you never call rect.__str__() yourself; Python calls it automatically whenever something needs a string representation of the object, most commonly str(rect) or print(rect). Without defining __str__, print(rect) would show something unhelpful like <Rectangle object at 0x...> — a memory address, not useful information about the rectangle itself.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def __str__(self):
return f"{self.width}x{self.height}"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.