ITPub博客

首页 > 应用开发 > Python > 如何在 Python 中自定义一个不可变的数据结构?

如何在 Python 中自定义一个不可变的数据结构?

原创 Python 作者:mingtian66 时间:2024-11-04 10:53:41 0 删除 编辑

在 Python 中,可以使用多种方式创建不可变的数据结构。不可变的数据结构意味着一旦创建,就无法修改其中的数据。下面介绍几种实现不可变数据结构的方式:
1. 使用 namedtuple

namedtuple 是 collections 模块中的一个工厂函数,可以创建类似元组的不可变数据类型。它具有属性访问的特性,比普通的元组更具可读性。

示例代码:

python

from collections import namedtuple

# 定义一个不可变的数据结构 Point
Point = namedtuple('Point', ['x', 'y'])

# 创建实例
p = Point(1, 2)

print(p.x)  # 输出: 1
print(p.y)  # 输出: 2

# 尝试修改会抛出 AttributeError 错误
# p.x = 3  # AttributeError: can't set attribute

2. 使用 dataclasses 模块中的 frozen 参数

dataclass 是 Python 3.7 引入的模块,用于创建数据类。通过设置 frozen=True,可以让数据类变成不可变的。

示例代码:

python

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

# 创建实例
p = Point(1, 2)

print(p.x)  # 输出: 1
print(p.y)  # 输出: 2

# 尝试修改会抛出 FrozenInstanceError 错误
# p.x = 3  # FrozenInstanceError: cannot assign to field 'x'

3. 使用 typing.NamedTuple(Python 3.6+)

typing.NamedTuple 是 namedtuple 的一种改进版,支持类型注解。它也是不可变的,并且提供了类型安全的功能。

示例代码:

python

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

# 创建实例
p = Point(1, 2)

print(p.x)  # 输出: 1
print(p.y)  # 输出: 2

# 尝试修改会抛出 AttributeError 错误
# p.x = 3  # AttributeError: can't set attribute

4. 自定义类并重写 __setattr__ 方法

可以通过自定义类并重写 __setattr__ 方法来实现不可变性,从而禁止对实例属性的修改。

示例代码:

python

class ImmutablePoint:
    def __init__(self, x, y):
        super().__setattr__('x', x)
        super().__setattr__('y', y)

    def __setattr__(self, key, value):
        raise AttributeError(f"{self.__class__.__name__} is immutable")

# 创建实例
p = ImmutablePoint(1, 2)

print(p.x)  # 输出: 1
print(p.y)  # 输出: 2

# 尝试修改会抛出 AttributeError 错误
# p.x = 3  # AttributeError: ImmutablePoint is immutable

5. 使用 __slots__ 限制属性并配合 property

可以使用 __slots__ 限制类属性,同时用 property 只定义只读的访问器方法,避免动态添加属性。

示例代码:

python

class ImmutablePoint:
    __slots__ = ('_x', '_y')

    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

# 创建实例
p = ImmutablePoint(1, 2)

print(p.x)  # 输出: 1
print(p.y)  # 输出: 2

# 尝试修改会抛出 AttributeError 错误
# p.x = 3  # AttributeError: can't set attribute

总结

这些方法都是在 Python 中实现不可变数据结构的有效方式。对于简单的结构可以用 namedtuple 或 NamedTuple,如果需要更丰富的功能,可以选择 dataclass(frozen=True)。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3045080/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    603270