作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
为什么 Python 本身不支持记录类型?这是一个可变版本的命名元组的问题。
我可以使用 namedtuple._replace
。但是我需要将这些记录放在一个集合中,并且由于 namedtuple._replace
创建了另一个实例,我还需要修改这个很快就会变得困惑的集合。
背景:我有一个设备,我需要通过 TCP/IP 轮询它来获取它的属性。即它的表示是一个可变对象。
编辑:我有一组需要轮询的设备。
编辑:我需要使用 PyQt 遍历显示其属性的对象。我知道我可以添加特殊方法,如 __getitem__
和 __iter__
,但我想知道是否有更简单的方法。
编辑:我更喜欢属性是固定的(就像它们在我的设备中一样)但可变的类型。
最佳答案
你的意思是这样的?
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)
请注意,提供的方法只是可能方法的一个示例。
您可以使用 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/
这实际上是我问的问题的一部分here ,该问题没有得到答复,最终被标记为重复。 问题:我只需使用 @Autowired 注释即可使用 JavaMailSender。我没有通过任何配置类公开它。 @Co
我是一名优秀的程序员,十分优秀!