Bỏ qua đến nội dung

CP4 - Prototype - Học Design Pattern Từ Những Thứ Đơn Giản

Con robot gắn bó lâu năm có đầy ký ức mà dây chuyền bình thường không sản xuất được. Tìm hiểu Prototype trong Python và lỗi deepcopy kinh điển.

Hoang Yell
Hoang Yell
5 phút đọc
English
CP4 - Prototype - Học Design Pattern Từ Những Thứ Đơn Giản

Prototype là một mẫu thiết kế nhóm Creational: 🖤🤍🤍🤍🤍 (Độ hữu dụng trong Python: 1/5)

Prototype là gì?

Prototype là kỹ thuật giúp nhân bản (clone) một object có sẵn thay vì khởi tạo lại từ đầu.

Tại sao dùng Prototype?

  • Để copy nguyên xi một object đang có.
  • Thực tế bạn không cần học Prototype kiểu GoF trong Python, vì module copy tích hợp sẵn làm hết việc này rồi.
    • Mọi object trong Python đều clone được bằng copy.
    • Lưu ý: ví dụ ghi đè def __deepcopy__ trên refactoring.guru vừa rườm rà vừa sai logic. Đừng copy theo họ, cứ dùng thẳng module copy chuẩn của Python.

Hỏi: Vậy… bài blog này viết ra để làm gì?

Đáp: Để bạn biết là không cần cày Prototype trong Python, đọc xong rồi nhảy qua pattern tiếp theo cho nhanh.

Khi nào dùng Prototype?

Hỏi: Khi nào thì tôi đang dùng Prototype?

Đáp: Mỗi lần bạn gọi copy.copy hoặc copy.deepcopy, chính là bạn đang dùng Prototype rồi.

Đầu vào:

  • Có sẵn một object gốc Robot
  • Tạo bản sao copied_robot từ origin_robot:
    • Dùng (shallow) copy:
      • copied_robot.mutable ↔️ dùng chung tham chiếu với origin_robot.mutable
    • Dùng deepcopy:
      • copied_robot.mutable 🛡️ tách độc lập hoàn toàn với origin_robot.mutable

Đọc thêm về mutable và immutable trong Python

import copy


class MemoryRobot:
    def __init__(self):
        self.who_am_i = None

    def set_memory(self, who_am_i):
        self.who_am_i = who_am_i


class Robot:
    def __init__(self, age, body_parts, memory):
        self.age = age
        self.body_parts = body_parts
        self.memory = memory

    @property
    def id(self):
        # https://www.digitalocean.com/community/tutorials/python-id
        return str(id(self))[-3:]


if __name__ == "__main__":

    def init_robot():
        robot_body_parts = [
            "head",
            {"left hand", "chest", "right hand"},
            ["left foot", "butt", "right foot"],
        ]
        memory_robot = MemoryRobot()
        robot = Robot(18, robot_body_parts, memory_robot)
        memory_robot.set_memory(robot)
        return robot

    def copy_robot(origin_robot, copy_method):
        wing = "wing"
        tail = "tail"
        tab = "    "
        tab_2 = "    " * 2
        tab_3 = "    " * 3
        print(f"\nCopying by {copy_method.__name__}:")
        copied_robot = copy_method(origin_robot)
        copied_robot.body_parts.append(tail)
        is_origin_robot_changed = origin_robot.body_parts[-1] == tail
        print(f"{tab}Question: update copied_robot changes origin_robot?")
        print(f"{tab_2}Answer: {is_origin_robot_changed}")

        origin_robot.body_parts[1].add(wing)
        is_copied_robot_changed = wing in copied_robot.body_parts[1]
        print(f"{tab}Question: update origin_robot changes copied_robot?")
        print(f"{tab_2}Answer: {is_copied_robot_changed}")

        print(f"{tab}How about reference?")
        print(f"{tab_2}origin_robot reference:")
        print(f"{tab_3}{origin_robot.id} is the ID of origin_robot")
        print(
            f"{tab_3}{origin_robot.memory.who_am_i.id} is the ID of origin_robot.memory.who_am_i"
        )
        print(f"{tab_2}copied_robot reference:")
        print(f"{tab_3}{copied_robot.id} is the ID of copied_robot")
        print(
            f"{tab_3}{copied_robot.memory.who_am_i.id} is the ID of copied_robot.memory.who_am_i"
        )
        return copied_robot

    origin_robot_1 = init_robot()
    shallow_copied_robot = copy_robot(origin_robot_1, copy.copy)

    origin_robot_2 = init_robot()
    deep_copied_robot = copy_robot(origin_robot_2, copy.deepcopy)

Kết quả mong muốn:

Copying by copy:
    Question: update copied_robot changes origin_robot?
        Answer: True
    Question: update origin_robot changes copied_robot?
        Answer: True
    How about reference?
        origin_robot reference:
            100 is the ID of origin_robot
            100 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            101 is the ID of copied_robot
            100 is the ID of copied_robot.memory.who_am_i

Copying by deepcopy:
    Question: update copied_robot changes origin_robot?
        Answer: False
    Question: update origin_robot changes copied_robot?
        Answer: False
    How about reference?
        origin_robot reference:
            200 is the ID of origin_robot
            200 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            201 is the ID of copied_robot
            201 is the ID of copied_robot.memory.who_am_i

So sánh cách triển khai:

Cách viết sai trên Refactoring.guru:

class Robot:
    ...

    def __copy__(self):
        body_parts = copy.copy(self.body_parts)
        memory = copy.copy(self.memory)
        copied_robot = self.__class__(self.age, body_parts, memory)
        copied_robot.__dict__.update(self.__dict__)
        return copied_robot

    def __deepcopy__(self, _=None):
        if _ is None:
            _ = {}
        body_parts = copy.deepcopy(self.body_parts, _)
        memory = copy.deepcopy(self.memory, _)
        copied_robot = self.__class__(self.age, body_parts, memory)
        copied_robot.__dict__ = copy.deepcopy(self.__dict__, _)
        return copied_robot
    ...

Cách viết này sai ở đoạn deepcopy:

  • copied_robot ID là 401 nhưng copied_robot.memory.who_am_i lại có ID 402 (khác nhau!).
  • Lý do: Nó tạo copied_robot mà quên đăng ký _[id(self)] = copied_robot vào memo dict trước khi deepcopy self.memory, làm tham chiếu vòng (circular reference) đẻ ra thêm một bản Robot thừa.
Copying by copy:
    Question: update copied_robot changes origin_robot?
        Answer: True
    Question: update origin_robot changes copied_robot?
        Answer: True
    How about reference?
        origin_robot reference:
            300 is the ID of origin_robot
            300 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            301 is the ID of copied_robot
            300 is the ID of copied_robot.memory.who_am_i

Copying by deepcopy:
    Question: update copied_robot changes origin_robot?
        Answer: False
    Question: update origin_robot changes copied_robot?
        Answer: False
    How about reference?
        origin_robot reference:
            400 is the ID of origin_robot
            400 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            401 is the ID of copied_robot
            402 is the ID of copied_robot.memory.who_am_i

Source Code: Incorrect Implement

Cách triển khai Prototype chuẩn trong Python:

Bạn đang dùng nó ở phần Đầu vào với copy.deepcopy sẵn rồi, không cần viết thêm dòng nào!

# nothing here

Source Code: Correct Implement


Điều hướng series: Trước: CP3 - Builder · Tiếp theo: CP5 - Singleton

Bài viết liên quan

yell@hoangyell:~ %

>hoangyell --status

Đang bận chở vợ con đi cafe & chơi với AI ☕🤖

Ủa ai réo Yell đấy? Cần tâm sự chuyện code hay collab thì ghé Instagram tui nè:

Ghé Instagram esc to close