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

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

    Python 3.7 onwards

    In Python 3.7, you may (ab)use the dataclass decorator, available from the dataclasses module. From the documentation:

    This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

    The member variables to use in these generated methods are defined using PEP 526 type annotations. For example this code:

    @dataclass
    class InventoryItem:
        '''Class for keeping track of an item in inventory.'''
        name: str
        unit_price: float
        quantity_on_hand: int = 0
    
        def total_cost(self) -> float:
            return self.unit_price * self.quantity_on_hand
    

    Will add, among other things, a __init__() that looks like:

    def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
          self.name = name
          self.unit_price = unit_price
          self.quantity_on_hand = quantity_on_hand
    

    Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.

    If your class is large and complex, it may be inappropriate to use a dataclass. I'm writing this on the day of release of Python 3.7.0, so usage patterns are not yet well established.

提交回复
热议问题