是否有一个简单设置属性的__init__的Python快捷方式?

nai*_*eai 10 python class shortcut python-2.7

在Python中有时候看到这样的__init__代码很常见:

class SomeClass(object):
    def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.f = f
        self.g = g
Run Code Online (Sandbox Code Playgroud)

特别是如果有问题的类纯粹是没有行为的数据结构.是否有一个(Python 2.7)快捷方式或一个方法来制作一个?

unu*_*tbu 11

你可以使用Alex Martelli的束配方:

class Bunch(object):
    """
    foo=Bunch(a=1,b=2)
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)
Run Code Online (Sandbox Code Playgroud)

  • 正如[彼得伍德建议](http://stackoverflow.com/questions/40545922/is-there-a-python-shortcut-for-an-init-that-simply-sets-properties/40545993?noredirect=1#comment68330675_40545922 ),如果你想要固定数量的命名属性,请使用[namedtuple](https://docs.python.org/2/library/collections.html#collections.namedtuple). (4认同)

Ala*_*air 8

您可能会发现attrs库很有帮助.以下是文档概述页面中的示例:

>>> import attr
>>> @attr.s
... class C(object):
...     x = attr.ib(default=42)
...     y = attr.ib(default=attr.Factory(list))
...
...     def hard_math(self, z):
...         return self.x * self.y * z
>>> i = C(x=1, y=2)
>>> i
C(x=1, y=2)
Run Code Online (Sandbox Code Playgroud)