是否有一种方法可以方便地在Python中定义类c结构?我厌倦了写这样的东西:

class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

当前回答

使用命名元组,该元组被添加到Python 2.6标准库中的collections模块中。如果你需要支持Python 2.4,也可以使用Raymond Hettinger的命名元组配方。

它适用于基本示例,但也适用于稍后可能遇到的一些边缘情况。你上面的片段可以写成:

from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")

新创建的类型可以这样使用:

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

你也可以使用命名参数:

m = MyStruct(field1="foo", field2="bar", field3="baz")

其他回答

https://stackoverflow.com/a/32448434/159695在Python3中不起作用。

https://stackoverflow.com/a/35993/159695在Python3中工作。

然后我扩展它来添加默认值。

class myStruct:
    def __init__(self, **kwds):
        self.x=0
        self.__dict__.update(kwds) # Must be last to accept assigned member variable.
    def __repr__(self):
        args = ['%s=%s' % (k, repr(v)) for (k,v) in vars(self).items()]
        return '%s(%s)' % ( self.__class__.__qualname__, ', '.join(args) )

a=myStruct()
b=myStruct(x=3,y='test')
c=myStruct(x='str')

>>> a
myStruct(x=0)
>>> b
myStruct(x=3, y='test')
>>> c
myStruct(x='str')

这里有一个解决方案,它使用一个类(从未实例化)来保存数据。我喜欢这种方式涉及很少的输入,不需要任何额外的软件包等。

class myStruct:
    field1 = "one"
    field2 = "2"

您可以稍后根据需要添加更多字段:

myStruct.field3 = 3

要获取值,可以像往常一样访问字段:

>>> myStruct.field1
'one'

dF:太酷了……我没有 我知道我可以访问的领域 一个使用字典的类。 马克:我希望我遇到的情况 这正是我需要一个元组的时候 但没有什么比 字典。

你可以使用字典访问类的字段,因为类的字段、它的方法和它的所有属性都是用字典存储在内部的(至少在CPython中是这样)。

...这就引出了你的第二个评论。相信Python字典是“沉重的”是一个非常非Python主义的概念。读这样的评论简直要了我的Python禅。这可不太好。

您可以看到,当您声明一个类时,实际上是在为一个字典创建一个相当复杂的包装器——因此,如果有的话,您比使用一个简单的字典增加了更多的开销。顺便说一下,这种开销在任何情况下都是没有意义的。如果您正在处理性能关键的应用程序,请使用C或其他语言。

我还想添加一个使用插槽的解决方案:

class Point:
    __slots__ = ["x", "y"]
    def __init__(self, x, y):
        self.x = x
        self.y = y

Definitely check the documentation for slots but a quick explanation of slots is that it is python's way of saying: "If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these slotted attributes".

添加属性到类实例的例子(因此不使用插槽):

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(3,5)
p1.z = 8
print(p1.z)

输出:8

尝试向使用插槽的类实例添加属性的示例:

class Point:
    __slots__ = ["x", "y"]
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(3,5)
p1.z = 8

'Point'对象没有属性'z'

这可以有效地作为结构体工作,并且比类使用更少的内存(就像结构体一样,尽管我没有研究具体有多少内存)。如果要创建对象的大量实例且不需要添加属性,建议使用slot。点对象就是一个很好的例子,因为很可能会实例化许多点来描述一个数据集。

你可以用元组来做很多你在C语言中使用结构体的事情(比如x,y坐标或RGB颜色)。

对于其他任何东西,你可以使用字典,或像这样的实用程序类:

>>> class Bunch:
...     def __init__(self, **kwds):
...         self.__dict__.update(kwds)
...
>>> mystruct = Bunch(field1=value1, field2=value2)

我认为“权威”的讨论在这里,在Python Cookbook的出版版本中。