python – how to define a structure like in C

python – how to define a structure like in C

Unless theres something special about your situation that youre not telling us, just use something like this:

class stru:
    def __init__(self):
        self.a = 0
        self.b = 0

s = stru()
s.a = 10


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). Theres a lot of room for improvement but if you find yourself doing this sort of stuff alot, it would pay for itself.

python – how to define a structure like in C

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

Leave a Reply

Your email address will not be published.