在python中复制struct

2024-04-20 06:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

python中是否有支持结构的方法,它是否不支持普通关键字struct?在

例如:

struct node
{
  unsigned dist[20];
  unsigned from[20];
}rt[10];

如何将其转换为python结构?在


Tags: 方法fromnodedist关键字结构structrt
3条回答

由于属性的顺序(除非使用OrderedDict或其他东西来__prepare__或以其他方式构建类)不一定是按定义的顺序排列的,如果您想与实际的C struct兼容,或者依赖数据的某种顺序,那么下面是您应该能够使用的基础(使用ctypes)。在

from ctypes import Structure, c_uint

class MyStruct(Structure):
    _fields_ = [
        ('dist', c_uint * 20),
        ('from', c_uint * 20)
    ]

我认为Python相当于C-structs是^{}

class Node:
    def __init__(self):
        self.dist_ = []
        self.from_ = []

rt = []

即使是空类也可以:

In [1]: class Node: pass
In [2]: n = Node()
In [3]: n.foo = [1,2,4]
In [4]: n.bar = "go"
In [8]: print n.__dict__
{'foo': [1, 2, 4], 'bar': 'go'}
In [9]: print n.bar
go

相关问题 更多 >