Lớp và đối tượng trong Python
Lớp và đối tượng là hai khía cạnh chính trong lập trình hướng đối tượng. Một lớp là một khuôn mẫu mà từ đó các đối tượng riêng lẻ được tạo ra. Trong thực tế, có hàng nghìn chiếc xe ô tô đang tồn tại có cùng kiểu dáng. Mỗi chiếc xe đều được sản xuất từ một bản thiết kế và do đó chưa các thành phần giống nhau. Theo thuật ngữ hướng đối tượng, chúng ta có thể nói rằng mỗi chiếc xe là một thể hiện (đối tượng) của lớp Car.
Python là ngôn ngữ lập trình hướng đối tượng, mọi thứ đều là đối tượng – int, float, double, string, list hay thậm chí bản thân các lớp.
Ví dụ: khi chúng ta khai báo str = “Hello”, Python sẽ tạo ra đối tượng mới kiểu string có giá trị là “Hello” và gán tham chiếu của nó đến tên biến str.
Nội dung của bài
Tạo một lớp
Để tạo một lớp chúng ta cần sử dụng từ khóa class.
Giả sử bạn muốn tạo các đối tượng biểu diễn thông tin về các loại xe ô tô. Mỗi đối tượng đại diện cho một ô tô duy nhất. Trước tiên, bạn cần xác định một lớp có tên là Car
class Car:
pass
Lớp Car như ví dụ trên là một đối tượng trống, chúng ta sử dụng câu lệnh pass để chỉ ra rằng lớp này trống.
Phương thức __init__()
class Car:
# initializer
def __init__(self):
pass
__init __ () là phương thức đặc biệt khởi tạo một đối tượng riêng lẻ. Phương thức này chạy tự động mỗi khi một đối tượng của một lớp được tạo.
Phương thức __init __ () thường được sử dụng để thực hiện các hoạt động cần thiết trước khi đối tượng được tạo.
Khi bạn định nghĩa init () trong định nghĩa lớp, tham số đầu tiên của nó phải là self.
Tham số self
Tham số self ánh xạ đến chính đối tượng riêng lẻ. Nó được sử dụng truy xuất hoặc thiết lập các thuộc tính của phiên bản cụ thể.
Thông số này không nhất thiết phải được gọi là self, chúng ta có thể đặt một tên bất kỳ, nhưng self được sử dụng rộng rãi và như một tiêu chuẩn mà chúng ta có thể tuân theo.
Attributes – Thuộc tính
Tất cả các class chúng ta viết trong Python hai tính năng cơ bản là attributes và methods.
Thuộc tính (Attributes) là những đặc điểm riêng lẻ để phân biệt một đối tượng này với đối tượng khác.
Ví dụ, trong class Car chúng ta có thể định nghĩa một số thuộc tính:
- Style: Sedan, SUV.
- Color: Black, White, Red.
Các thuộc tính chúng ta khai báo trong class là các biến, trong mỗi đối tượng các biến này sẽ có giá trị nhất định.
Trong Python có 2 loại thuộc tính là Instance attributes và Class attributes.
Instance attributes
Instance attribute là biến bắt buộc với mỗi đối tượng. Tất cả đối tượng phải khởi tạo giá trị cho các thuộc tính này. Khi chúng ta thay đổi giá trị của các thuộc tính này ở các đối tượng không làm ảnh hưởng đến các đối tượng khác.
Trong ví dụ chúng ta đang nói đến, mỗi ô tô có màu và kiểu dáng nhất định.
class Car:
# khởi tạo với instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
Class Attribute
Thuộc tính lớp là biến mà chúng ta sử dụng chung cho tất cả các đối tượng. Khi thay đổi giá trị này sẽ ảnh hướng đến tất cả các đối tượng khác.
Trong lơp Car, mỗi ô tô có 4 bánh.
class Car:
# class attribute
wheels = 4
# khởi tạo với instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
Như vậy, mỗi ô tô có kiểu dáng và màu sắc khác nhau nhưng đều có 4 bánh.
Tạo đối tượng
Chúng ta có thể tạo một đối tượng bằng cách gọi tên class và truyền vào các tham số cần thiết.
class Car:
# class attribute
wheels = 4
# khỏi tạo with instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
mazda3 = Car('Sedan', 'Black')
Chúng ta vừa tạo một đối tượng từ lớp Car với các tham số truyền vào cho các thuộc tính color và style. Python sẽ tự động nhận biết self là gì (đối tượng mazda3) và chuyển đến phương thức __init()__.
Truy xuất và cập nhật thuộc tính
class Car:
# class attribute
wheels = 4
# khỏi tạo with instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
mazda3 = Car('Sedan', 'Black')
# access attributes
print(mazda3.color)
# Prints Black
# cập nhật giá trị cho các thuộc tính
mazda3.color = "White"
print(mazda3.color)
# Prints White
Cài đặt các phương thức
Trong ví dụ trên chúng ta cập nhật thuộc tính color của đối tượng mazda3: mazda3.color = “White”
Chúng ta có thể xây dựng phương thức để thực hiện việc này.
class Car:
# class attribute
wheels = 4
# initializer / instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
def changeColor(self, color):
self.color = color
mazda3 = Car('Sedan', 'Black')
mazda3.changeColor("Red")
print(mazda3.color)
# Prints Red
Video demo
Tổng kết
Trong lập trình hướng đối tượng thì chúng ta thường xuyên phải sử dụng class và object. Các bạn hãy thực hành thuần thục kiến thức trong bài này nhé.