Khi cần tính diện tích hình chữ nhật sử dụng lớp, phương pháp hướng đối tượng giúp tổ chức code rõ ràng, tái sử dụng dễ dàng.
Ví dụ
class Rectangle:
"""Lớp đại diện cho hình chữ nhật."""
def __init__(self, length, width):
"""
Khởi tạo hình chữ nhật.
Args:
length (float): Chiều dài (> 0)
width (float): Chiều rộng (> 0)
"""
if length <= 0 or width <= 0:
raise ValueError("Chiều dài và chiều rộng phải lớn hơn 0")
self.length = length
self.width = width
def area(self):
"""Tính diện tích: dài × rộng"""
return self.length * self.width
def perimeter(self):
"""Tính chu vi: 2 × (dài + rộng)"""
return 2 * (self.length + self.width)
def diagonal(self):
"""Tính đường chéo: √(dài² + rộng²)"""
import math
return math.sqrt(self.length ** 2 + self.width ** 2)
def is_square(self):
"""Kiểm tra có phải hình vuông không."""
return self.length == self.width
def scale(self, factor):
"""Phóng to/thu nhỏ hình chữ nhật (trả về instance mới)."""
return Rectangle(self.length * factor, self.width * factor)
def __str__(self):
return f"Hình chữ nhật {self.length} × {self.width}"
def __repr__(self):
return f"Rectangle(length={self.length}, width={self.width})"
def __eq__(self, other):
if not isinstance(other, Rectangle):
return False
return self.length == other.length and self.width == other.width
# Sử dụng
length = 6
width = 45
print(f"Chiều dài: {length}")
print(f"Chiều rộng: {width}")
rect = Rectangle(length, width)
print(f"\n{rect}")
print(f"Diện tích: {rect.area()}")
print(f"Chu vi: {rect.perimeter()}")
print(f"Đường chéo: {rect.diagonal():.2f}")
print(f"Là hình vuông? {rect.is_square()}")
Kết quả
Chiều dài: 6 Chiều rộng: 45 Hình chữ nhật 6 × 45 Diện tích: 270 Chu vi: 102 Đường chéo: 45.40 Là hình vuông? False
Giải thích
- Lớp
Rectanglecó thuộc tínhlengthvàwidth. - Phương thức
area()tính diện tích =length * width. - Phương thức
perimeter()tính chu vi =2 * (length + width). - Validate input trong
__init__đảm bảo chiều dài, rộng > 0. - Magic methods cho phép so sánh
==, in đẹp, v.v.
Sử dụng với nhiều hình chữ nhật
rectangles = [
Rectangle(3, 4),
Rectangle(5, 5), # Hình vuông
Rectangle(10, 2),
Rectangle(7, 8),
]
print(f"{'Hình':<20} {'Diện tích':>10} {'Chu vi':>10} {'Vuông?'}")
print("-" * 50)
for r in rectangles:
print(f"{str(r):<20} {r.area():>10} {r.perimeter():>10} {r.is_square()}")
# Sắp xếp theo diện tích
rectangles_sorted = sorted(rectangles, key=lambda r: r.area())
print(f"\nHình có diện tích nhỏ nhất: {rectangles_sorted[0]}")
print(f"Hình có diện tích lớn nhất: {rectangles_sorted[-1]}")
Dataclass (Python 3.7+) - code ngắn gọn hơn
from dataclasses import dataclass
import math
@dataclass
class RectangleDC:
length: float
width: float
def __post_init__(self):
if self.length <= 0 or self.width <= 0:
raise ValueError("Chiều dài và rộng phải > 0")
@property
def area(self):
return self.length * self.width
@property
def perimeter(self):
return 2 * (self.length + self.width)
@property
def diagonal(self):
return math.hypot(self.length, self.width)
# Sử dụng
r = RectangleDC(6, 45)
print(r.area) # 270 (gọi như attribute nhờ @property)
print(r.perimeter) # 102