將類別加入套件

Python 的軟體工程原則

Adam Spannbauer

Machine Learning Engineer at Eastman

物件導向程式設計

OOP 模組化

Python 的軟體工程原則

類別結構剖析

work_dir/my_package/my_class.py 作業

# Define a minimal class with an attribute
class MyClass:

"""A minimal example class :param value: value to set as the ``attribute`` attribute :ivar attribute: contains the contents of ``value`` passed in 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
Python 的軟體工程原則

在套件中使用類別

work_dir/my_package/__init__.py 作業

from .my_class import MyClass

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'
Python 的軟體工程原則

self 慣例

work_dir/my_package/my_class.py 作業

# Define a minimal class with an attribute
class MyClass:
    """A minimal example class

    :param value: value to set as the ``attribute`` attribute
    :ivar attribute: contains the contents of ``value`` passed in 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')
Python 的軟體工程原則

一起來練習吧!

Python 的軟體工程原則

Preparing Video For Download...