Python 可变 NamedTuple

标签 python struct python-3.6 mutable namedtuple

我正在寻找一种类似结构的数据结构,我可以从中创建多个实例并具有某种类型提示而不是不可变的。

所以我有这样的东西:

class ConnectionConfig(NamedTuple):
    name: str
    url: str
    port: int
    user: str = ""
    pwd: str = ""
    client: Any = None

但我想让它可变。我可以这样做:

class ConnectionConfig():
    def __init__(self, name: str, url: str, port: int, user: str = "", pwd: str = "", client: Any = None):
        self.name = name
        self.url = url
        self.port = port
        self.user = user
        self.pwd = pwd
        self.client = client

但是天哪...这太丑了:/python 中有内置的替代品吗? (使用Python 3.6.3)

最佳答案

实际上,您的实现是(唯一)内置的方法:

class ConnectionConfig():
    def __init__(self, name: str, url: str, port: int, user: str = "",
                 pwd: str = "", client: Any = None):
        pass

阅读PEP 0484我还没有找到任何其他适合您需求的替代方案。继续 PEP 链,我猜这句话来自 PEP 20 The Zen of Python解释一下:

There should be one-- and preferably only one --obvious way to do it.

关于Python 可变 NamedTuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865909/

相关文章:

python - 与 sleep 命令相比,使用循环在 python 中等待更多 CPU 密集型?

python - Spark 读取二进制文件的子组

python - Odoo:检查是否安装了模块

struct - 为具有 From 类型的结构实现 PartialEq

c - 带有 typedef 的结构

linux - 关于Python3.6 os.urandom/os.getrandom/secrets的问题

Python 从普通函数调用协程

python - Dijkstra 的算法问题和 python 中的关键错误

c - 如何测试 FILE*(指向结构的指针)(如果 == NULL)?

Python3.6 : Error importing gi module