Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (19k points)

Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:

class MyStruct():

def __init__(self, field1, field2, field3):

self.field1 = field1

self.field2 = field2

self.field3 = field3

1 Answer

0 votes
by (106k points)

For C-like structures in Python, you can use a named tuple, which was added to the collections module in the standard library in Python 2.6. 

from collections import namedtuple

MyStruct = namedtuple("MyStruct", "field1 field2 field3")

The named tuple can be used like this:

m = MyStruct("foo", "bar", "baz")

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...