Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a data type in Python similar to structs in C++?

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.

like image 948
Aufwind Avatar asked May 09 '11 22:05

Aufwind


People also ask

What is the C struct equivalent in Python?

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.

Is there a struct in Python?

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.

How do you define a struct 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.

Is struct a data type in C?

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.


2 Answers

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__.

like image 67
ThiefMaster Avatar answered Sep 20 '22 20:09

ThiefMaster


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 
like image 44
sock Avatar answered Sep 16 '22 20:09

sock