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

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

    You could also do:

    locs = locals()
    for arg in inspect.getargspec(self.__init__)[0][1:]:
        setattr(self, arg, locs[arg])
    

    Of course, you would have to import the inspect module.

提交回复
热议问题