gpt4 book ai didi

python - 为什么 Python 不支持记录类型? (即可变的命名元组)

转载 作者:IT老高 更新时间:2023-10-28 20:34:07 28 4
gpt4 key购买 nike

为什么 Python 本身不支持记录类型?这是一个可变版本的命名元组的问题。

我可以使用 namedtuple._replace。但是我需要将这些记录放在一个集合中,并且由于 namedtuple._replace 创建了另一个实例,我还需要修改这个很快就会变得困惑的集合。

背景:我有一个设备,我需要通过 TCP/IP 轮询它来获取它的属性。即它的表示是一个可变对象。

编辑:我有一组需要轮询的设备。

编辑:我需要使用 PyQt 遍历显示其属性的对象。我知道我可以添加特殊方法,如 __getitem____iter__,但我想知道是否有更简单的方法。

编辑:我更喜欢属性是固定的(就像它们在我的设备中一样)但可变的类型。

最佳答案

Python <3.3

你的意思是这样的?

class Record(object):
__slots__= "attribute1", "attribute2", "attribute3",

def items(self):
"dict style items"
return [
(field_name, getattr(self, field_name))
for field_name in self.__slots__]

def __iter__(self):
"iterate over fields tuple/list style"
for field_name in self.__slots__:
yield getattr(self, field_name)

def __getitem__(self, index):
"tuple/list style getitem"
return getattr(self, self.__slots__[index])

>>> r= Record()
>>> r.attribute1= "hello"
>>> r.attribute2= "there"
>>> r.attribute3= 3.14

>>> print r.items()
[('attribute1', 'hello'), ('attribute2', 'there'), ('attribute3', 3.1400000000000001)]
>>> print tuple(r)
('hello', 'there', 3.1400000000000001)

请注意,提供的方法只是可能方法的一个示例。

Python ≥3.3 更新

您可以使用 types.SimpleNamespace :

>>> import types
>>> r= types.SimpleNamespace()
>>> r.attribute1= "hello"
>>> r.attribute2= "there"
>>> r.attribute3= 3.14

dir(r) 将为您提供属性名称(当然,过滤掉所有 .startswith("__"))。

关于python - 为什么 Python 不支持记录类型? (即可变的命名元组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5227839/

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