为什么Python不支持记录类型? (即可变的namedtuple) [英] Why does Python not support record type? (i.e. mutable namedtuple)
问题描述
为什么Python本身不支持记录类型?有一个可变版本的namedtuple。
Why does Python not support a record type natively? It's a matter of having a mutable version of namedtuple.
我可以使用 namedtuple._replace
。但是我需要将这些记录保存在集合中,并且由于 namedtuple._replace
创建了另一个实例,因此我还需要修改集合,这会很快变得混乱。
I could use namedtuple._replace
. But I need to have these records in a collection and since namedtuple._replace
creates another instance, I also need to modify the collection which becomes messy quickly.
背景:
我有一台设备,需要通过在TCP / IP上对其进行轮询来获取其属性。即它的表示形式是可变对象。
Background: I have a device whose attributes I need to get by polling it over TCP/IP. i.e. its representation is a mutable object.
编辑:
我有一组需要轮询的设备。
I have a set of devices for whom I need to poll.
编辑:
我需要使用PyQt遍历显示其属性的对象。我知道我可以添加特殊方法,例如 __ getitem __
和 __ iter __
,但是我想知道是否有更简单的方法。
I need to iterate through the object displaying its attributes using PyQt. I know I can add special methods like __getitem__
and __iter__
, but I want to know if there is an easier way.
编辑:
我更喜欢一种属性是固定的类型(就像它们在我的设备中一样),但是是可变的。
I would prefer a type whose attribute are fixed (just like they are in my device), but are mutable.
推荐答案
Python< 3.3
您的意思是这样的吗?
Python <3.3
You mean something like this?
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)
您可以使用< a href = http://docs.python.org/py3k/library/types.html#types.SimpleNamespace rel = noreferrer> types.SimpleNamespace
:
You can use types.SimpleNamespace
:
>>> import types
>>> r= types.SimpleNamespace()
>>> r.attribute1= "hello"
>>> r.attribute2= "there"
>>> r.attribute3= 3.14
dir(r)
会为您提供属性名称(当然会过滤掉所有 .startswith( __)
)。
dir(r)
would provide you with the attribute names (filtering out all .startswith("__")
, of course).
这篇关于为什么Python不支持记录类型? (即可变的namedtuple)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!