8

I have this C code:

    typedef struct test * Test;

    struct test {
        void *a;
        Test next;
    };

How would you implement the equivalent to this in Python (if that is even possible)?

3
  • 2
    @Eddy_Em What do you smoke right now? Commented May 23, 2013 at 19:38
  • @glglgl, maybe you can tell me how can I make strict variable type in python? For example: float a; char *b; void *f; double t;? Commented May 23, 2013 at 19:40
  • 1
    @Eddy_Em What does this have to do with "being a real programming language"? And why shouldn't it not be possible? Look at the linked "duplicate" question or the answer below - here you see how it would work. Commented May 23, 2013 at 19:48

1 Answer 1

20

In Python, you can assign objects of any type to a variable; so you can just use any class, like this:

class test(object):
    __slots__ = ['a', 'next']

x = test()
x.next = x
x.a = 42

Note that __slots__ is optional and should reduce memory overhead (it may also speed up attribute access). Also, you often want to create a constructor, like this:

class test(object):
    def __init__(self, a, next):
        self.a = a
        self.next = next

x = test(21, None)
assert x.a == 21

If the class can be immutable, you may also want to have a look at namedtuple:

import collections
test = collections.namedtuple('test', ['a', 'next'])
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not positive that __slots__ makes the code run any faster in general (although I suppose it might). Generally it is used to save memory if you're going to be instantiating hordes of simple objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.