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

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

    To expand on gruszczys answer, I have used a pattern like:

    class X:
        x = None
        y = None
        z = None
        def __init__(self, **kwargs):
            for (k, v) in kwargs.items():
                if hasattr(self, k):
                    setattr(self, k, v)
                else:
                    raise TypeError('Unknown keyword argument: {:s}'.format(k))
    

    I like this method because it:

    • avoids repetition
    • is resistant against typos when constructing an object
    • works well with subclassing (can just super().__init(...))
    • allows for documentation of the attributes on a class-level (where they belong) rather than in X.__init__

    Prior to Python 3.6, this gives no control over the order in which the attributes are set, which could be a problem if some attributes are properties with setters that access other attributes.

    It could probably be improved upon a bit, but I'm the only user of my own code so I am not worried about any form of input sanitation. Perhaps an AttributeError would be more appropriate.

提交回复
热议问题