In Python, there isn't a built-in basic type specifically for rectangles (like Rect in some other languages). However, you can represent a rectangle in several ways depending on your needs:
Common Ways to Represent a Rectangle in Python:
-
Using a Tuple or List:
You can represent a rectangle as a tuple or list of coordinates (e.g., (x, y, width, height) or (x1, y1, x2, y2)).
rect = (10, 20, 100, 50) # (x, y, width, height)
-
Using a Dictionary:
You can use a dictionary to store rectangle properties with named keys.
rect = {"x": 10, "y": 20, "width": 100, "height": 50}
-
Using a Class:
You can define a custom Rect class to encapsulate rectangle properties and methods.
class Rect:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
rect = Rect(10, 20, 100, 50)
-
Using collections.namedtuple:
For a lightweight immutable rectangle type, you can use namedtuple.
from collections import namedtuple
Rect = namedtuple("Rect", ["x", "y", "width", "height"])
rect = Rect(10, 20, 100, 50)
-
Using External Libraries:
Example with a Custom Rect Class:
Here’s a simple example of a custom Rect class with basic functionality:
class Rect:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __repr__(self):
return f"Rect(x={self.x}, y={self.y}, width={self.width}, height={self.height})"
# Usage
rect = Rect(10, 20, 100, 50)
print(rect.area()) # Output: 5000
Summary:
- Python does not have a built-in
Rect type, but you can easily create one using tuples, dictionaries, classes, or libraries like Pygame.
- For most use cases, a tuple or a custom class is sufficient. If you're working with graphics or games, Pygame's
Rect is very convenient.