← 返回目录

第三章:函数与面向对象

函数、模块、类与 dataclass

1. 函数与参数

def greet(name: str, *, loud: bool = False) -> str:
    msg = f"Hello, {name}"
    return msg.upper() if loud else msg

* 之后为仅关键字参数,利于 API 稳定性。

2. 模块

包目录需含 __init__.py(Python 3.3+ 命名空间包可省略,但显式更清晰)。

from pathlib import Path
import mypkg.utils as u

3. 类与 dataclass

from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    active: bool = True

4. Protocol(结构化子类型)

from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

无需继承即可满足接口:符合「鸭子类型」+ 静态检查。

📋 本章要点

函数签名、模块组织、@dataclassProtocol 是现代 Python 工程常用组合。

评论加载中...