2024-09-28 05:20:49 发布
网友
在Python中,经常会看到这样的__init__代码:
__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)的快捷方式或者一种制作方法?在
您可以使用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)
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)
您可以使用Alex Martelli的Bunch recipe:
当然可以。在
和
v = SomeClass(a=1, b=2, c=3, d=4)
这会使你的代码难以理解。在
祝你好运。在
您可能会发现attrs库很有用。以下是来自文档的overview page的示例:
相关问题 更多 >
编程相关推荐