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

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

    This is a solution without any additional imports.

    Helper function

    A small helper function makes it more convenient and re-usable:

    def auto_init(local_name_space):
        """Set instance attributes from arguments.
        """
        self = local_name_space.pop('self')
        for name, value in local_name_space.items():
            setattr(self, name, value)
    

    Application

    You need to call it with locals():

    class A:
        def __init__(self, x, y, z):
            auto_init(locals())
    

    Test

    a = A(1, 2, 3)
    print(a.__dict__)
    

    Output:

    {'y': 2, 'z': 3, 'x': 1}
    

    Without changing locals()

    If you don't like to change locals() use this version:

    def auto_init(local_name_space):
        """Set instance attributes from arguments.
        """
        for name, value in local_name_space.items():
            if name != 'self': 
                setattr(local_name_space['self'], name, value)
    

提交回复
热议问题