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

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

    As others have mentioned, the repetition isn't bad, but in some cases a namedtuple can be a great fit for this type of issue. This avoids using locals() or kwargs, which are usually a bad idea.

    from collections import namedtuple
    # declare a new object type with three properties; x y z
    # the first arg of namedtuple is a typename
    # the second arg is comma-separated or space-separated property names
    XYZ = namedtuple("XYZ", "x, y, z")
    
    # create an object of type XYZ. properties are in order
    abc = XYZ("one", "two", 3)
    print abc.x
    print abc.y
    print abc.z
    

    I've found limited use for it, but you can inherit a namedtuple as with any other object (example continued):

    class MySuperXYZ(XYZ):
        """ I add a helper function which returns the original properties """
        def properties(self):
            return self.x, self.y, self.z
    
    abc2 = MySuperXYZ(4, "five", "six")
    print abc2.x
    print abc2.y
    print abc2.z
    print abc2.properties()
    

提交回复
热议问题