How do I avoid the “self.x = x; self.y = y; self.z = z” pattern in __init__?

后端 未结 11 1554
醉梦人生
醉梦人生 2020-12-12 11:16

I see patterns like

def __init__(self, x, y, z):
    ...
    self.x = x
    self.y = y
    self.z = z
    ...

quite frequently, often with

11条回答
  •  臣服心动
    2020-12-12 11:23

    explicit is better than implicit ... so sure you could make it more concise:

    def __init__(self,a,b,c):
        for k,v in locals().items():
            if k != "self":
                 setattr(self,k,v)
    

    The better question is should you?

    ... that said if you want a named tuple I would recommend using a namedtuple (remember tuples have certain conditions attached to them) ... perhaps you want an ordereddict or even just a dict ...

提交回复
热议问题