Thêm lớp vào package

Nguyên tắc Kỹ thuật Phần mềm với Python

Adam Spannbauer

Machine Learning Engineer at Eastman

Lập trình hướng đối tượng

Tính mô-đun OOP

Nguyên tắc Kỹ thuật Phần mềm với Python

Cấu trúc của một lớp

làm việc trong work_dir/my_package/my_class.py

# Define a minimal class with an attribute
class MyClass:

"""Một lớp ví dụ tối giản :param value: giá trị gán cho thuộc tính ``attribute`` :ivar attribute: chứa nội dung của ``value`` truyền vào init """
# Method to create a new instance of MyClass def __init__(self, value): # Define attribute with the contents of the value param self.attribute = value
Nguyên tắc Kỹ thuật Phần mềm với Python

Dùng lớp trong package

làm việc trong work_dir/my_package/__init__.py

from .my_class import MyClass

làm việc trong work_dir/my_script.py

import my_package

# Create instance of MyClass
my_instance = my_package.MyClass(value='class attribute value')

# Print out class attribute value
print(my_instance.attribute)
'class attribute value'
Nguyên tắc Kỹ thuật Phần mềm với Python

Quy ước self

làm việc trong work_dir/my_package/my_class.py

# Define a minimal class with an attribute
class MyClass:
    """Một lớp ví dụ tối giản

    :param value: giá trị gán cho thuộc tính ``attribute``
    :ivar attribute: chứa nội dung của ``value`` truyền vào init
    """

    # Method to create a new instance of MyClass
    def __init__(self, value):
        # Define attribute with the contents of the value param
        self.attribute = value
my_instance = my_package.MyClass(value='class attribute value')
Nguyên tắc Kỹ thuật Phần mềm với Python

Hãy thực hành

Nguyên tắc Kỹ thuật Phần mềm với Python

Preparing Video For Download...