有没有一种用构造函数参数实例化 class 的简短方法?

Is there a short way to instantiate a class with the constructor params?

我正在使用 python 3.4

class baba():
  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

有没有更短的写法? 除了将所有这些作为字典获取之外

您可以使用 **kwargs,然后使用 setattr 创建您的实例属性:

class baba():
    def __init__(self, **kwargs):
        for i in kwargs:
            setattr(self, i, kwargs[i])

b = baba(a=1,b=2,c=4,d=5)
print(b.a) # prints 1