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.
You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example). I think the "definitive" discussion is here, in the published version of the Python Cookbook. dF. dF.
The struct module in Python is used to convert native Python data types such as strings and numbers into a string of bytes and vice versa. What this means is that users can parse binary files of data stored in C structs in Python.
Structs are defined using a mini language based on format strings that allows you to define the arrangement of various C data types like char , int , and long as well as their unsigned variants. Serialized structs are seldom used to represent data objects meant to be handled purely inside Python code.
A structure is a key word that create user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to create a structure? 'struct' keyword is used to create a structure.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With