Đọc (read) file JSON với Python
1. JSON (JavaScript Object Notation) là gì? JSON (JavaScript Object Notation) là một định dạng (format)...
Kết quả sẽ mở trong tab mới, giới hạn trong website này.
Truy cập nhanh
Tìm kiếm gần đây
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 […]
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.
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 đó,
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()
Tom cat has grey and white color
Milk cat has black and white color
Trong 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)
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
Traceback (most recent call last):
File "c:\python-examples\example.py", line 20, in <module>
del tom.species
AttributeError: species
Trong Python, có 3 dạng hàm khởi tạo là:
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()
Catch mouse.
Take a nap.
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()
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 color
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()
Tom cat has grey and white color
Milk cat has black and white color
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()
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.5
Lư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.
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()
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'
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()
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'