萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 3 快速入門:模組化與類別程式設計

一、模組化:組織可維護的程式碼

專案結構範例

project/
├── main.py              # 入口
├── utils/
│   ├── __init__.py      # 使目錄成為套件
│   └── math_ops.py
└── models/
    ├── __init__.py
    └── user.py

匯入與使用

# main.py
import utils.math_ops
from models.user import User

print(utils.math_ops.add(1, 2))

u = User('Alice', 30)
u.greet()

`__init__.py` 作用

  • 標記目錄為 Python 套件 (Package)
  • 可執行初始化程式碼、定義 `__all__` 控制 `from pkg import *`
  • Python 3.3+ 支援**隱含命名空間套件** (無 `__init__.py` 也可),但建議保留

實用內建函數

  • `dir(module)`:列出模組公開屬性
  • `module.__name__`:模組名稱
  • `help(module)`:查看文件字串

二、作用域與 `global` / `nonlocal`

def scope_test():
    spam = 'test spam'
    
    def do_local():
        spam = 'local spam'          # 新區域變數
    
    def do_nonlocal():
        nonlocal spam                # 綁定外層 (非全域) 變數
        spam = 'nonlocal spam'
    
    def do_global():
        global spam                  # 綁定模組層級全域變數
        spam = 'global spam'
    
    do_local()
    print('After local:', spam)      # test spam
    do_nonlocal()
    print('After nonlocal:', spam)   # nonlocal spam
    do_global()
    print('After global:', spam)     # global spam

scope_test()
print('In global:', spam)            # global spam

三、類別基礎

定義與實例化

class Person:
    # 類別屬性 (共享)
    species = 'Human'
    
    def __init__(self, name, age):
        # 實例屬性 (各自獨立)
        self.name = name
        self.age = age
        print('Constructor called')
    
    def greet(self):
        print(f'Hi, I am {self.name}, {self.age} years old.')
    
    def __repr__(self):
        return f'Person({self.name!r}, {self.age})'

p1 = Person('Wang', 20)
p1.greet()
print(p1)  # 觸發 __repr__

`self` 慣例

Python 將實例方法的第一個參數慣例命名為 `self` (對應 C++/Java `this`)。呼叫 `p1.greet()` 實際轉為 `Person.greet(p1)`。

繼承與多型

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)  # 呼叫父類建構子
        self.student_id = student_id
    
    def greet(self):                 # 覆寫
        super().greet()
        print(f'  Student ID: {self.student_id}')

s = Student('Li', 19, 'S2024001')
s.greet()

多重繼承與 MRO

class A: pass
class B: pass
class C(A, B): pass

print(C.__mro__)  # (C, A, B, object)
# Python 3 皆為新式類 (隱含繼承 object),使用 C3 線性化演算法

預設參數替代多載

Python 不支援傳統多載 (同名不同參數),改用**預設參數**或 `*args/**kwargs`:

def connect(host, port=80, timeout=5, **options):
    ...

connect('localhost')
connect('localhost', 8080)
connect('localhost', timeout=10, ssl=True)

屬性裝飾器:受控存取

class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError('Radius cannot be negative')
        self._radius = value
    
    @property
    def area(self):
        return 3.14159 * self._radius ** 2

c = Circle(5)
print(c.area)      # 唯讀屬性
c.radius = 10      # 觸發 setter 驗證

四、模組與類別的最佳實務

copyright © 萬盛學電腦網 all rights reserved
原則說明
單一職責一個模組/類別只做一件事
命名慣例模組 `snake_case`、類別 `PascalCase`、常數 `UPPER_SNAKE`
私有慣例`_single` 內部使用、`__double` 名稱修飾 (非真私有)
文件字串模組、類別、函數皆寫 `"""docstring"""`
型別提示Python 3.5+ `def f(x: int) -> str:` 提升可讀度與靜態分析