Is there a data type in Python similar to structs in C++?
Why not? Classes are fine for that.
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.
For example, a class holding only two values (a
and b
) could looks like this:
class AB(object): __slots__ = ('a', 'b')
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__
.
In addition to the dict type, there is a namedtuple type that behaves somewhat like a struct.
MyStruct = namedtuple('MyStruct', ['someName', 'anotherName'])aStruct = MyStruct('aValue', 'anotherValue')print aStruct.someName, aStruct.anotherName
dataclass
is now built-in to Python as of Python 3.7!
from dataclasses import dataclass@dataclassclass EZClass: name: str='default' qty: int
Test:
classy = EZClass('cars', 3)print(classy)
Output:
EZClass(name='cars', qty=3)
Besides for the automatic initialization and __repr__
methods which it generates, it also automatically creates an __eq__
method to make it simple and intuitive to compare two instances of the class.
See PEP 557.
Backported to Python 3.6 using the dataclasses package.