为什么Python本身不支持记录类型?这是拥有一个可变版本的namedtuple的问题。

我可以使用namedtuple._replace。但是我需要将这些记录保存在一个集合中,并且因为namedtuple._replace创建了另一个实例,所以我还需要修改变得非常困惑的集合。

背景:
我有一台设备,需要通过在TCP/IP上对其进行轮询来获取其属性。即它的表示形式是可变对象。

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

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

编辑:
我希望其属性是固定的(就像它们在我的设备中一样)但可变的。

最佳答案

Python
你的意思是这样的吗?

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("__")过滤掉)。

09-10 03:21
查看更多