gpt4 book ai didi

Python 可变 NamedTuple

转载 作者:行者123 更新时间:2023-11-30 22:27:36 25 4
gpt4 key购买 nike

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

所以我有这样的东西:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com