Python 如何定义像在C中一样的结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3648442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to define a structure like in C
提问by Bin Chen
I am going to define a structure and pass it into a function:
我将定义一个结构并将其传递给一个函数:
In C:
在 C 中:
struct stru {
int a;
int b;
};
s = new stru()
s->a = 10;
func_a(s);
How this can be done in Python?
这如何在 Python 中完成?
采纳答案by Nathan Davis
Unless there's something special about your situation that you're not telling us, just use something like this:
除非您没有告诉我们您的情况有什么特别之处,否则只需使用以下内容:
class stru:
def __init__(self):
self.a = 0
self.b = 0
s = stru()
s.a = 10
func_a(s)
回答by aaronasterling
use named tuples if you are ok with an immutable type.
如果您对不可变类型没问题,请使用命名元组。
import collections
struct = collections.namedtuple('struct', 'a b')
s = struct(1, 2)
Otherwise, just define a class if you want to be able to make more than one.
否则,如果您希望能够创建多个类,只需定义一个类。
A dictionary is another canonical solution.
字典是另一种规范的解决方案。
If you want, you can use this function to create mutable classes with the same syntax as namedtuple
如果需要,您可以使用此函数创建具有相同语法的可变类 namedtuple
def Struct(name, fields):
fields = fields.split()
def init(self, *values):
for field, value in zip(fields, values):
self.__dict__[field] = value
cls = type(name, (object,), {'__init__': init})
return cls
you might want to add a __repr__method for completeness. call it like s = Struct('s', 'a b'). sis then a class that you can instantiate like a = s(1, 2). There's a lot of room for improvement but if you find yourself doing this sort of stuff alot, it would pay for itself.
您可能想要添加一个__repr__完整的方法。称之为s = Struct('s', 'a b'). s然后是一个可以实例化的类,例如a = s(1, 2). 有很大的改进空间,但如果你发现自己经常做这类事情,那它就会物有所值。
回答by Rafael Sierra
回答by Rafe Kettler
Sorry to answer the question 5 days later, but I think this warrants telling.
很抱歉在 5 天后回答这个问题,但我认为这值得说明。
Use the ctypesmodule like so:
ctypes像这样使用模块:
from ctypes import *
class stru(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
]
When you need to do something C-like (i.e. C datatypes or even use C DLLs), ctypesis the module. Also, it comes standard
当你需要做一些类似 C 的事情(即 C 数据类型或什至使用 C DLL)时,ctypes就是模块。此外,它是标准的
回答by skif_engineer
(for future google-searchers): the most C/C++ way of doing it - is to use class without constructor:
(对于未来的谷歌搜索者):最 C/C++ 的做法是使用没有构造函数的类:
class my_struct:
name = ''
health = 0.0
count = 0
values_list = [1,2,3]
s1 = my_struct()
s1.count = 5
s1.name = 'some string'
s1.health = 0.1
s1.values_list = [4,5,6]
print s1.name
# some string

