how to define a structure like in C [duplicate]
I am going to define a structure and pass it into a function:
In C:
struct stru {
int a;
int b;
};
s = new stru()
s->a = 10;
func_a(s);
How this can be done in Python?
Unless there's something special about your situation that you're not telling us, just use something like this:
class stru:
def __init__(self):
self.a = 0
self.b = 0
s = stru()
s.a = 10
func_a(s)
use named tuples if you are ok with an immutable type.
import collections
struct = collections.namedtuple('struct', 'a b')
s = struct(1, 2)
Otherwise, just define a class if you want to be able to make more than one.
A dictionary is another canonical solution.
If you want, you can use this function to create mutable classes with the same syntax as namedtuple
def Struct(name, fields):
fields = fields.split()
def init(self, *values):
for field, value in zip(fields, values):
self.__dict__[field] = value
cls = type(name, (object,), {'__init__': init})
return cls
you might want to add a __repr__
method for completeness. call it like s = Struct('s', 'a b')
. s
is then a class that you can instantiate like a = s(1, 2)
. There's a lot of room for improvement but if you find yourself doing this sort of stuff alot, it would pay for itself.
Sorry to answer the question 5 days later, but I think this warrants telling.
Use the ctypes
module like so:
from ctypes import *
class stru(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
]
When you need to do something C-like (i.e. C datatypes or even use C DLLs), ctypes
is the module. Also, it comes standard
Use classes and code Python thinking in Python, avoid to just write the same thing but in another syntax.
If you need the struct by how it's stored in memory, try module struct
精彩评论