有没有一个简化属性设置的Python __init__快捷方式?

2024-09-28 05:20:49 发布

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

在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

尤其是如果所讨论的类纯粹是一个没有行为的数据结构。有没有一个(python2.7)的快捷方式或者一种制作方法?在


Tags: 代码self数据结构objectinitdefclass快捷方式
3条回答

您可以使用Alex Martelli的Bunch recipe

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

当然可以。在

Class SomeClass(object):
    def __init__(self, **args):
        for(k, v) in args.items():
            setattr(self, k, v)

v = SomeClass(a=1, b=2, c=3, d=4)

这会使你的代码难以理解。在

祝你好运。在

您可能会发现attrs库很有用。以下是来自文档的overview page的示例:

>>> 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)

相关问题 更多 >

    热门问题