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)
您可能会发现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)