Python: Iterating through constructor's arguments

前端 未结 9 2075
囚心锁ツ
囚心锁ツ 2021-02-05 15:07

I often find myself writing class constructors like this:

class foo:
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
         


        
9条回答
  •  天涯浪人
    2021-02-05 15:54

    For python >= 3.7 take a look at the @dataclass class decorator. Among other things, it handles your __init__ boilerplate coding problem.

    From the doc:

    @dataclass
    class InventoryItem:
        name: str
        unit_price: float
        quantity_on_hand: int = 0
    

    Will automatically add an __init__ like that:

    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
    

提交回复
热议问题