class Point:
"""二维点坐标"""
# 类属性(所有实例共享)
dimension = 2
def __init__(self, x: float, y: float):
# 实例属性
self.x = x
self.y = y
def distance(self, other: 'Point') -> float:
"""计算两点距离"""
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
def __repr__(self) -> str:
returnf"Point({self.x}, {self.y})"
def __eq__(self, other) -> bool:
returnself.x == other.x andself.y == other.y
# 使用示例
p1 = Point(3, 4)
p2 = Point(0, 0)
print(p1.distance(p2)) # 5.0from collections import namedtuple
# 创建轻量级不可变类型
Person = namedtuple('Person', ['name', 'age', 'job'])
person = Person("拾光", 18, "Test")
print(person.age)
print(person._asdict())
# 类型注解支持
class Person(namedtuple('Person', ['name', 'age', 'job'])):
__annotations__ = {'name': str, 'age': int, 'job': str}from dataclasses import dataclass, field
from typing importList
@dataclass(order=True, frozen=False)
class InventoryItem:
"""商品库存项"""
name: str
price: float = field(compare=False) # 不参与比较
quantity: int = 0
tags: List[str] = field(default_factory=list)
def total_value(self) -> float:
returnself.price * self.quantity
# 自动生成的方法:__init__, __repr__, __eq__
item = InventoryItem("Laptop", 999.99, 5)
print(item) # InventoryItem(name='Laptop', price=999.99, quantity=5, tags=[])from enum import Enum, auto, unique
@unique # 确保值唯一
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# 自动赋值
YELLOW = auto()
def rgb(self) -> tuple:
return {
Color.RED: (255, 0, 0),
Color.GREEN: (0, 255, 0),
Color.BLUE: (0, 0, 255),
Color.YELLOW: (255, 255, 0)
}[self]
# 使用
print(Color.RED.rgb()) # (255, 0, 0)
print(list(Color)) # [<Color.RED: 1>, ...]from typing import Dict, Tuple, List
# 基本别名
UserId = int
UserData = Dict[str, str]
# 复杂结构
Coordinates = Tuple[float, float]
Path = List[Coordinates]
def process_path(path: Path) -> None:
for x, y in path:
print(f"({x}, {y})")from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsArea(Protocol):
def area(self) -> float: ...
class Circle:
def __init__(self, radius: float):
self.radius = radius
def area(self) -> float:
return 3.14 * self.radius ** 2
def print_area(obj: SupportsArea) -> None:
print(f"Area: {obj.area()}")
# 无需继承,只要实现 area 方法
print_area(Circle(5)) # Area: 78.5from typing import TypeVar, Generic, List
T = TypeVar('T') # 任意类型
N = TypeVar('N', int, float) # 数字类型
class Stack(Generic[T]):
def __init__(self):
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
returnself.items.pop()
# 使用
int_stack = Stack[int]()
int_stack.push(42)from typing import Union
def parse_input(value: Union[int, str]) -> int:
if isinstance(value, str):
return int(value.strip())
return value
# Python 3.10+ 以上支持
def parse_input(value: int | str) -> int:
...from typing import Final
MAX_SIZE: Final[int] = 100
# MAX_SIZE = 200 # 类型检查器会报错
class DatabaseConfig:
HOST: Final[str] = "localhost"
PORT: Final[int] = 5432#Python #Python自定义数据类型