Khi cần quản lý danh sách (thêm, xóa, hiển thị) sử dụng lớp, lập trình hướng đối tượng giúp đóng gói dữ liệu và hành vi.
Ví dụ
class ListManager:
"""Lớp quản lý danh sách với các thao tác cơ bản."""
def __init__(self):
"""Khởi tạo danh sách rỗng."""
self._items = [] # Dùng _items để chỉ internal use
def add(self, value):
"""Thêm phần tử vào cuối danh sách."""
self._items.append(value)
return self # Cho phép method chaining
def remove(self, value):
"""Xóa phần tử đầu tiên có giá trị value."""
try:
self._items.remove(value)
return True
except ValueError:
return False
def remove_at(self, index):
"""Xóa phần tử tại vị trí index."""
if 0 <= index < len(self._items):
del self._items[index]
return True
return False
def display(self):
"""Trả về bản sao danh sách (tránh sửa đổi ngoài)."""
return self._items.copy()
def __len__(self):
return len(self._items)
def __contains__(self, item):
return item in self._items
def __str__(self):
return str(self._items)
def __repr__(self):
return f"ListManager({self._items})"
# Chương trình tương tác
def main():
manager = ListManager()
menu = """
=== QUẢN LÝ DANH SÁCH ===
1. Thêm phần tử
2. Xóa phần tử (theo giá trị)
3. Xóa phần tử (theo vị trí)
4. Hiển thị danh sách
5. Kiểm tra phần tử tồn tại
6. Độ dài danh sách
0. Thoát
"""
while True:
print(menu)
try:
choice = int(input("Chọn chức năng (0-6): "))
if choice == 1:
val = input("Nhập giá trị cần thêm: ")
# Thử chuyển số nếu có thể
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass # Giữ nguyên string
manager.add(val)
print(f"Đã thêm. Danh sách: {manager.display()}")
elif choice == 2:
if not manager._items:
print("Danh sách rỗng!")
continue
val = input("Nhập giá trị cần xóa: ")
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass
if manager.remove(val):
print(f"Đã xóa {val}. Danh sách: {manager.display()}")
else:
print(f"Không tìm thấy {val} trong danh sách.")
elif choice == 3:
if not manager._items:
print("Danh sách rỗng!")
continue
idx = int(input("Nhập vị trí cần xóa (0-based): "))
if manager.remove_at(idx):
print(f"Đã xóa tại vị trí {idx}. Danh sách: {manager.display()}")
else:
print("Vị trí không hợp lệ.")
elif choice == 4:
print(f"Danh sách hiện tại: {manager.display()}")
elif choice == 5:
val = input("Nhập giá trị cần kiểm tra: ")
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass
print(f"{val} {'có' if val in manager else 'không có'} trong danh sách.")
elif choice == 6:
print(f"Độ dài danh sách: {len(manager)}")
elif choice == 0:
print("Tạm biệt!")
break
else:
print("Lựa chọn không hợp lệ!")
except ValueError:
print("Vui lòng nhập số.")
except KeyboardInterrupt:
print("\nTạm biệt!")
break
if __name__ == "__main__":
main()
Kết quả mẫu
=== QUẢN LÝ DANH SÁCH === 1. Thêm phần tử 2. Xóa phần tử (theo giá trị) 3. Xóa phần tử (theo vị trí) 4. Hiển thị danh sách 5. Kiểm tra phần tử tồn tại 6. Độ dài danh sách 0. Thoát Chọn chức năng (0-6): 1 Nhập giá trị cần thêm: 34 Đã thêm. Danh sách: [34] Chọn chức năng (0-6): 3 Danh sách hiện tại: [34] Chọn chức năng (0-6): 2 Nhập giá trị cần xóa: 34 Đã xóa 34. Danh sách: [] Chọn chức năng (0-6): 0 Tạm biệt!
Giải thích
- Lớp
ListManagerđóng gói list nội bộ_items. - Các phương thức:
add(),remove(),remove_at(),display(). - Magic methods:
__len__,__contains__,__str__,__repr__cho phép dùnglen(),in,print()tự nhiên. - Method chaining:
add()trả vềselfcho phépmgr.add(1).add(2). - Xử lý input linh hoạt: tự nhận diện int/float/string.
- Xử lý ngoại lệ: list rỗng, index sai, giá trị không tồn tại.
Mở rộng: Undo/Redo
class UndoableListManager(ListManager):
def __init__(self):
super().__init__()
self._history = []
self._future = []
def _save_state(self):
self._history.append(self._items.copy())
self._future.clear()
def add(self, value):
self._save_state()
return super().add(value)
def remove(self, value):
if value in self._items:
self._save_state()
return super().remove(value)
return False
def undo(self):
if self._history:
self._future.append(self._items.copy())
self._items = self._history.pop()
return True
return False
def redo(self):
if self._future:
self._history.append(self._items.copy())
self._items = self._future.pop()
return True
return False