Hướng dẫn python str init - python str init

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 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.

Nội dung chính

  • 2. Các dạng hàm khởi tạo của class trong Python
  • 2.1. Hàm khởi tạo mặc định (default constructor)
  • 2.2. Hàm khởi tạo không có tham số (non-parametrized constructor)
  • 2.3. Hàm khởi tạo có tham số (parameterized constructor)
  • 2.4. Hàm constructor với các giá trị mặc định (default values)
  • 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
  • 3.2. Python không cho phép hàm __init__() return giá trị

Nội dung chính

  • 2. Các dạng hàm khởi tạo của class trong Python
  • 2.1. Hàm khởi tạo mặc định (default constructor)
  • 2.2. Hàm khởi tạo không có tham số (non-parametrized constructor)
  • 2.3. Hàm khởi tạo có tham số (parameterized constructor)
  • 2.4. Hàm constructor với các giá trị mặc định (default values)
  • 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
  • 3.2. Python không cho phép hàm __init__() return giá trị

Nội dung chính

  • 2. Các dạng hàm khởi tạo của class trong Python
  • 2.1. Hàm khởi tạo mặc định (default constructor)
  • 2.2. Hàm khởi tạo không có tham số (non-parametrized constructor)
  • 2.3. Hàm khởi tạo có tham số (parameterized constructor)
  • 2.4. Hàm constructor với các giá trị mặc định (default values)
  • 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
  • 3.2. Python không cho phép hàm __init__() return giá trị

Hàm

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()
9 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
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()
9. 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.
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()
9
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
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()
9
. 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

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()
9 trong Python:
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()
9
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 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) 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 đó. 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. 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.species và các thuộc tính của từng đối tượng là namecolor.

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 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 đó.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 namecolor 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.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 
    print("name of tom:", tom.name)
AttributeError: 'Cat' object has no attribute 'name'

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 đó., 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 
    del tom.species
AttributeError: species

2. Các dạng hàm khởi tạo của class trong Python

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.
  • Nhưng lưu ý, Python không cho phép xóa thuộc tính của class.
  • Trong Python, có 3 dạng hàm khởi tạo là:

2.1. Hàm khởi tạo mặc định (default constructor)

Hàm khởi tạo mặc định (default constructor)__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.

Hàm khởi tạo không có tham số (non-parametrized constructor): 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-parametrized constructor)

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 đó.__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-parametrized 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-parametrized 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-parametrized 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ả
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()
0

2.3. Hàm khởi tạo có tham số (parameterized constructor)

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 đó.__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"

  # 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()
1
Kết quả
Tom cat has grey and white color
Milk cat has black and white color

2.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.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:
  # 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()
3
Kết quả
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()
4

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. 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.

  • Kỹ thuật lập trình với kiểu cấu trúc và con trỏ trong C++
  • Khai báo đối tượng (object) trong lập trình hướng đối tượng (OOP)
  • Đọc (read) file JSON với Python
  • Xóa (delete) dữ liệu trong MySQL với PHP
  • Cách tạo mảng (array) và thao tác với mảng trong PHP

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:
  # 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()
5
Kết quả
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()
6

3.2. Python không cho phép hàm __init__() return giá trị

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()
7
Kết quả
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()
8