Hàm Khởi Tạo (constructor) __init__() Của Class Trong Python
Có thể bạn quan tâm
Trong bài này, chúng ta sẽ tìm hiểu về hàm khởi tạo (constructor) của class trong Python. Đây là bài tiếp theo của bài Xây dựng lớp (class) và tạo đối tượng (object) trong Python. Các bạn nên đọc trước bài này để nắm được các kiến thức cơ bản về class và object trong Python trước khi tìm hiểu về hàm __init__() trong Python.
1. Hàm __init__() trong Python
Hàm __init__() là hàm khởi tạo (constructor) của class trong Python. Tất cả các lớp trong Python đều có hàm __init__(). Hàm khởi tạo luôn luôn được gọi khi một đối tượng của một lớp được tạo ra. Hàm khởi tạo được sử dụng để gán giá trị cho các thuộc tính của đối tượng hoặc thực hiện một số thao tác khi đối tượng đang được tạo ra.
Cú pháp của hàm __init__() trong Python:def __init__(self, [parameter1, parameter2,...]): # Body of __init__()
Trong đó,
- def là từ khóa khai báo một hàm trong Python
- __init__() là tên của hàm khởi tạo (constructor)
- self là tham số đầu tiên của hàm __init__(). Đây là một tham chiếu đến đối tượng hiện tại của lớp và được sử dụng để truy cập các biến thuộc về lớp đó.
- [parameter1, parameter2,…] là các tham số tùy chọn, thường là các giá trị để gán cho các thuộc tính của đối tượng được tạo ra.
Ví dụ bên dưới là tạo một class Cat với thuộc tính của lớp là species và các thuộc tính của từng đối tượng là name và color.class Cat: # class attribute species = "cat" # constructor of class Cat # instance attribute def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") def catchMouse(self): print(self.name, "catch mouse.") def sleep(self): print(self.name, "take a nap.") tom = Cat("Tom", "grey and white") tom.catInfo() mycat = Cat("Milk", "black and white") mycat.catInfo()
Kết quả
Tom cat has grey and white color Milk cat has black and white colorTrong lớp Cat, thuộc tính species là thuộc tính của lớp. Thuộc tính của lớp sẽ có giá trị giống nhau cho tất cả đối tượng của lớp được tạo ra. Các thuộc tính name và color là các thuộc tính của đối tượng. Các thuộc tính của đối tượng sẽ khác nhau giữa các đối tượng được tạo ra của lớp đó.
Chúng ta có thể xóa các thuộc tính của đối tượng với từ khóa del.class Cat: # class attribute species = "cat" # constructor of class Cat # instance attribute def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") def catchMouse(self): print(self.name, "catch mouse.") def sleep(self): print(self.name, "take a nap.") tom = Cat("Tom", "grey and white") print("name of tom:", tom.name) del tom.name print("name of tom:", tom.name)
Kết quả
name of tom: Tom Traceback (most recent call last): File "c:\python-examples\example.py", line 22, in <module> print("name of tom:", tom.name) AttributeError: 'Cat' object has no attribute 'name'Nhưng lưu ý, Python không cho phép xóa thuộc tính của class.class Cat: # class attribute species = "cat" # constructor of class Cat # instance attribute def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") def catchMouse(self): print(self.name, "catch mouse.") def sleep(self): print(self.name, "take a nap.") tom = Cat("Tom", "grey and white") del tom.species
Kết quả
Traceback (most recent call last): File "c:\python-examples\example.py", line 20, in <module> del tom.species AttributeError: species2. Các dạng hàm khởi tạo của class trong Python
Trong Python, có 3 dạng hàm khởi tạo là:
- Hàm khởi tạo mặc định (default constructor)
- Hàm khởi tạo không có tham số (non-parameterized constructor)
- Hàm khởi tạo có tham số (parameterized constructor)

2.1. Hàm khởi tạo mặc định (default constructor)
Khi định nghĩa một class, nếu chúng ta không định nghĩa hàm khởi tạo __init__() thì tự tạo hàm này cho chúng ta. Hàm khởi tạo này được gọi là hàm khởi tạo mặc định (default constructor). Default constructor sẽ không thực thi bất cứ nhiệm vụ nào.
Lưu ý: Default constructor sẽ được Python tự động thêm vào class của chúng ta khi biên dịch. Nếu chúng ta đã định nghĩa một hàm khởi tạo trong class thì default constructor sẽ không được thêm vào class.class Cat: # class attribute species = "cat" # Methods of Cat class def catchMouse(self): print("Catch mouse.") def sleep(self): print("Take a nap.") tom = Cat() tom.catchMouse() tom.sleep()
Kết quả
Catch mouse. Take a nap.2.2. Hàm khởi tạo không có tham số (non-parameterized constructor)
Hàm __init__() không có bất kỳ tham số nào ngoài tham số self được gọi là hàm khởi tạo không có tham số (non-parameterized constructor). Hàm khởi tạo dạng này được sử dụng để tạo các đối tượng với các giá trị mặc định. Tức là các đối tượng khi mới được tạo ra thì hoàn toàn giống nhau.class Cat: # class attribute species = "cat" # non-parameterized constructor def __init__(self): self.name = "Tom" self.color = "grey and white" # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") # create objects of Cat class with non-parameterized constructor tom1 = Cat() print("Info of tom1:") tom1.catInfo() tom2 = Cat() print("Info of tom2:") tom2.catInfo() tom2.name = "Tom2" tom2.color = "black and white" print("Info of tom2 after changed:") tom2.catInfo()
Kết quả
Info of tom1: Tom cat has grey and white color Info of tom2: Tom cat has grey and white color Info of tom2 after changed: Tom2 cat has black and white color2.3. Hàm khởi tạo có tham số (parameterized constructor)
Hàm __init__() được định nghĩa có các tham số khác ngoài tham số self được gọi là hàm khởi tạo có tham số (parameterized constructor). Với parameterized constructor, chúng ta có thể truyền các giá trị khác nhau khi khởi tạo các đối tượng của một class.class Cat: # class attribute species = "cat" # parameterized constructor def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") # create objects of Cat class with parameterized constructor tom = Cat("Tom", "grey and white") tom.catInfo() mycat = Cat("Milk", "black and white") mycat.catInfo()
Kết quả
Tom cat has grey and white color Milk cat has black and white color2.4. Hàm constructor với các giá trị mặc định (default values)
Python cho phép chúng ta tạo một hàm khởi tạo với các giá trị mặc định (default values). Default values sẽ được sử dụng nếu chúng ta không truyền đối số cho hàm khởi tạo khi tạo đối tượng.class Cat: # parameterized constructor def __init__(self, cat_name, cat_color="grey and white", cat_weight=3.9): self.name = cat_name self.color = cat_color self.weight = cat_weight # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color, weight", self.weight) # create objects of Cat class with parameterized constructor tom = Cat("Tom") tom.catInfo() mycat = Cat("Milk", "black and white") mycat.catInfo() myfriendcat = Cat("MeoMeo", "black and white", 4.5) myfriendcat.catInfo()
Kết quả
Tom cat has grey and white color, weight 3.9 Milk cat has black and white color, weight 3.9 MeoMeo cat has black and white color, weight 4.5Lưu ý: Các tham số có giá trị mặc định phải được đặt bên phải các tham số không có giá trị mặc định nếu không Python sẽ báo lỗi.
- Chuỗi ký tự là gì? Cách khởi tạo và một số kỹ thuật lập trình trên chuỗi
- Thread là gì? Cách tạo Thread trong Java
- Hướng dẫn sử dụng phần mềm mô phỏng mạch điện tử Proteus
- Cách chạy một chương trình Java và các Java IDE thường dùng
- Sử dụng kiểu dữ liệu String trong Python
3. Một số lưu ý khi sử dụng hàm __init__() trong Python
3.1. Python không cho phép có nhiều hơn một hàm __init__() trong class
class Cat: # constructor with 1 parameter def __init__(self, cat_name): self.name = cat_name # constructor with 2 parameters def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") # create objects of Cat class tom = Cat("Tom") tom.catInfo()Kết quả
Traceback (most recent call last): File "c:\python-examples\example.py", line 15, in <module> tom = Cat("Tom") TypeError: Cat.__init__() missing 1 required positional argument: 'cat_color'3.2. Python không cho phép hàm __init__() return giá trị
class Cat: # constructor with 2 parameters and return def __init__(self, cat_name, cat_color): self.name = cat_name self.color = cat_color return True # Methods of Cat class def catInfo(self): print(self.name, "cat has", self.color, "color") # create objects of Cat class tom = Cat("Tom", "grey and white") tom.catInfo()Kết quả
Traceback (most recent call last): File "c:\python-examples\example.py", line 13, in <module> tom = Cat("Tom", "grey and white") TypeError: __init__() should return None, not 'bool' 4.8/5 - (5 bình chọn)Bài trước và bài sau trong môn học<< Xây dựng lớp (class) và tạo đối tượng (object) trong PythonKế thừa (inheritance) trong Python >>Từ khóa » Trong Python ý Nghĩa Của Hàm __init__() Trong Python Là Gì
-
Ý Nghĩa Của Hàm __init__() Trong Python Là Gì?
-
Ý Nghĩa Của Hàm __init__() Trong Python Là Gì? - Trắc Nghiệm Online
-
Ý Nghĩa Của Hàm __init__() Trong Python Là Gì? B. Được Gọi Khi Một ...
-
Hàm Tạo __init__ Trong Python - TEK4
-
Hàm __init__ Và Self Trong Python Dùng để Làm Gì? - Dạy Nhau Học
-
Ý Nghĩa Của Hàm __init__() Trong Python Là Gì? - .vn
-
Pygame __init__ Là Gì
-
Python __init__ Và Tự Làm Gì? - HelpEx
-
Hàm __init__ Và Self Trong Python Dùng để Làm Gì?
-
__Init__ Và Tự Làm Gì Trong Python? - HelpEx
-
Hàm Super() Trong Python
-
Bài 20: Hướng đối Tượng Trong Python - Lập Trình Python Cơ Bản
-
Tổng Quan Về Class Và Hàm Constructor Trong Lập Trình Python
-
Class Trong Python - Viblo