首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python自定义数据类型总结

python自定义数据类型总结

作者头像
小田测测看
发布2026-06-17 17:24:02
发布2026-06-17 17:24:02
640
举报

自定义数据类型

1. 传统类

代码语言:javascript
复制
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.0

2. namedtuple

代码语言:javascript
复制
from 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}

3. dataclass - Python 3.7+以上支持

代码语言:javascript
复制
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=[])

4. 枚举 (Enum)

代码语言:javascript
复制
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>, ...]

5. 类型别名 (Type Aliases)

代码语言:javascript
复制
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})")

自定义类型

1. 协议类型 (Protocol)

代码语言:javascript
复制
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.5

2. 泛型类型

代码语言:javascript
复制
from 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)

3. 联合类型

代码语言:javascript
复制
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:
    ...

4. Final和常量

代码语言:javascript
复制
from typing import Final

MAX_SIZE: Final[int] = 100
# MAX_SIZE = 200  # 类型检查器会报错

class DatabaseConfig:
    HOST: Final[str] = "localhost"
    PORT: Final[int] = 5432

#Python #Python自定义数据类型

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-07-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程拾光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 自定义数据类型
    • 1. 传统类
    • 2. namedtuple
    • 3. dataclass - Python 3.7+以上支持
    • 4. 枚举 (Enum)
    • 5. 类型别名 (Type Aliases)
  • 自定义类型
    • 1. 协议类型 (Protocol)
    • 2. 泛型类型
    • 3. 联合类型
    • 4. Final和常量
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档