Is this the only way to use structure for C in Python?

Asked 2 years ago, Updated 2 years ago, 134 views

Is this the only way to use structure for C in Python?

class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

I used to use C (I learned C a little bit, but...) and I'm just learning Python. Everyone else's code is short and easy, but why am I squeezing Python like C??

struct python

2022-09-22 14:47

1 Answers

Since you said C's structure, not C++ (no member function), I think you can use collections.namedtuple.

In C, collections.namedtuple(typename, field_names, verbose=False, rename=False) to the factor

That's all you need to think about.

For example, C code

struct MyStruct{
    int field1, field2, field3; // arbitrarily set to int type
}

is the following Python code

from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")

It's similar to the function.

When you actually write it,

m = MyStruct("foo", "bar", "baz")
m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz")

You can set the member variable together


2022-09-22 14:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.