【问题标题】:Is there a short way to instantiate a class with the constructor params? [duplicate]有没有一种用构造函数参数实例化类的捷径? [复制]
【发布时间】:2016-06-09 02:00:44
【问题描述】:

我正在使用 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

有没有更短的方法来写这个? 除了将所有这些都作为字典

【问题讨论】:

    标签: python python-3.x constructor method-parameters


    【解决方案1】:

    您可以使用**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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-27
      • 2017-09-04
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      相关资源
      最近更新 更多