Python中是否有类似于C ++中的结构的数据类型? [英] Is there a data type in Python similar to structs in C++?

查看:68
本文介绍了Python中是否有类似于C ++中的结构的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有类似于C ++中的结构的数据类型?我喜欢结构功能 myStruct.someName .我知道类具有此功能,但是我不想每次需要一些数据的容器"时都编写一个类.

Is there a data type in Python similar to structs in C++? I like the struct feature myStruct.someName. I know that classes have this, but I don't want to write a class everytime I need a "container" for some data.

推荐答案

为什么不呢?上课就可以了.

Why not? Classes are fine for that.

如果要节省一些内存,则可能还需要使用 __ slots __ ,以便对象没有 __ dict __ .请参见 http://docs.python.org/reference/datamodel.html#slots以获得详细信息,并使用__slots__?以获得一些有用的信息.

If you want to save some memory, you might also want to use __slots__ so the objects don't have a __dict__. See http://docs.python.org/reference/datamodel.html#slots for details and Usage of __slots__? for some useful information.

例如,仅包含两个值( a b )的类可能看起来像这样:

For example, a class holding only two values (a and b) could looks like this:

class AB(object):
    __slots__ = ('a', 'b')


如果您实际上想要一个字典,但具有 obj.item 而不是 obj ['item'] 的访问权限,则可以将dict子类化并实现 __ getattr __ __ setattr __ 的行为类似于 __ getitem __ __ setitem __ .


If you actually want a dict but with obj.item access instead of obj['item'], you could subclass dict and implement __getattr__ and __setattr__ to behave like __getitem__ and __setitem__.

这篇关于Python中是否有类似于C ++中的结构的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆