Reputation: 11
I'm pretty new to Python and I'm having difficulty figuring out how to use the structs. What would the C structs below look like when they are converted into Python?
These are the structs I have:
struct dataT
{
int m;
};
struct stack
{
int top;
struct dataT items[STACKSIZE];
} st;
How would this statement be represented in Python?
st.items[st.top].m
Upvotes: 1
Views: 62
Reputation: 30258
You can use namedtuples to construct classes that can represent your structs:
from collections import namedtuple
dataT = namedtuple("dataT", ['m'])
stack = namedtuple("stack", ['top', 'items'])
st = stack(0, [])
st.items.append(dataT(5))
st.items[st.top].m
Though you will probably find that the stack class is unnecessary as pointed out list already has this behaviour.
Upvotes: 0
Reputation: 117856
You just need to define your dataT
class
class dataT():
def __init__(self, m=0):
self.m = m
You can instantiate one like
d = dataT(5)
The stack
behavior you can get from the list
class already
>>> l = [dataT(i) for i in range(5)]
>>> l.pop().m
4
>>> l.pop().m
3
>>> l.pop().m
2
>>> l.pop().m
1
>>> l.pop().m
0
>>> l.append(dataT(3))
>>> l.pop().m
3
Upvotes: 2