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

后端 未结 11 1549
醉梦人生
醉梦人生 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:43

    My 0.02$. It is very close to Joran Beasley answer, but more elegant:

    def __init__(self, a, b, c, d, e, f):
        vars(self).update((k, v) for k, v in locals().items() if v is not self)
    

    Additionally, Mike Müller's answer (the best one to my taste) can be reduced with this technique:

    def auto_init(ns):
        self = ns.pop('self')
        vars(self).update(ns)
    

    And the just call auto_init(locals()) from your __init__

提交回复
热议问题