60 phút
Lập trình hướng đối tượng trong Python
Class và Object
Định nghĩa class
class Student:
# Constructor
def __init__(self, name, age, student_id):
self.name = name
self.age = age
self.student_id = student_id
self.grades = []
# Method
def introduce(self):
return f"Tôi là {self.name}, {self.age} tuổi, MSSV: {self.student_id}"
def add_grade(self, grade):
self.grades.append(grade)
def calculate_average(self):
if not self.grades:
return 0
return sum(self.grades) / len(self.grades)
# Tạo object
student1 = Student("Alice", 20, "SV001")
student2 = Student("Bob", 21, "SV002")
print(student1.introduce())
student1.add_grade(8.5)
student1.add_grade(9.0)
print(f"Điểm trung bình: {student1.calculate_average():.2f}")
Kế thừa (Inheritance)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Tôi là {self.name}, {self.age} tuổi"
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def teach(self):
return f"{self.name} đang dạy môn {self.subject}"
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
self.grades = []
def study(self):
return f"{self.name} đang học bài"
# Sử dụng
teacher = Teacher("Mr. Smith", 35, "Toán")
student = Student("Alice", 20, "SV001")
print(teacher.introduce())
print(teacher.teach())
print(student.introduce())
print(student.study())
Tính đóng gói (Encapsulation)
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.__balance = initial_balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
def get_account_info(self):
return f"Tài khoản: {self.account_holder}, Số dư: {self.__balance:,} VND"
# Sử dụng
account = BankAccount("John Doe", 1000000)
account.deposit(500000)
account.withdraw(200000)
print(account.get_account_info())
# print(account.__balance) # Lỗi! Không thể truy cập trực tiếp
Tính đa hình (Polymorphism)
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
class Cow(Animal):
def make_sound(self):
return "Moo!"
# Sử dụng đa hình
animals = [Dog(), Cat(), Cow()]
for animal in animals:
print(animal.make_sound())