0

I want to use struct on the python as like below C style.

typedef
{
  int a;
  int b;
}my_struct_t;

my_strut_t func(my_strut_t ttt, int var1, int var2)
{
  ttt.a = var1;
  ttt.b = var2;

  return ttt;
}

main()
{
  my_struct_t my_struct;

  my_struct = func(my_struct, 10, 20);

  printf("a=%d, b=%d", my_struct.a, my_struct.b);
}

Could you translate above C style code to python script?

Thank you.

spring79y
  • 179
  • 2
  • 2
  • 8
  • 5
    Possible duplicate of [C-like structures in Python](http://stackoverflow.com/questions/35988/c-like-structures-in-python) – Yevhen Kuzmovych Apr 27 '17 at 13:15
  • Consider using the [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) type. It was written explicitly to handle record types like this. – Noufal Ibrahim Apr 27 '17 at 13:18
  • 2
    @NoufalIbrahim that depends on the use case - because `namedtuple`s (as any `tuple` or `tuple`-like objects) are immutable. It would work for the code above, but not so much if the `my_struct` is meant to be mutated (a field's changed) somewhere else. – drdaeman Apr 27 '17 at 13:31

2 Answers2

0

You could make a class in python instead of a struct

class my_struct_t(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

def main():
    my_struct = my_struct_t(10, 20)
    print('a={}, b={}'.format(my_struct.a, my_struct.b))
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Use a class:

class Struct:
    pass

# or, equivalently:

Struct = type("Struct", (), {})

Then you can create members of that class on the fly:

test = Struct()

test.a = 5 # create a new member
print(test.a)

print(test.b) # Error: this member doesn't exist
# but you can create it easily

Then, once you create all the members necessary for each instance, you can pass the instances of this class around etc.

Be aware that newly initialized instances do not have any members except some default ones.

ForceBru
  • 43,482
  • 10
  • 63
  • 98