Implement packing/unpacking in an object

前端 未结 2 948
甜味超标
甜味超标 2020-12-03 15:39

I have a class that only contains attributes and I would like packing/unpacking to work on it. What collections.abc should I implement to get this behaviour?

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 16:20

    Another option would be a named tuple

    Item = collections.namedtuple('Item', ['name', 'age', 'gender']) 
    

    So this works out of the box:

    a, b, c = Item("Henry", 90, "male")
    

    If you're on Python 3.7+, you could also take advantage of dataclasses which are more powerful. But you would need to explicitly call astuple:

    @dataclasses.dataclass
    class Item(object):
        name: str
        age: int
        gender: str
    
    a, b, c = dataclasses.astuple(Item("Henry", 90, "male"))
    

提交回复
热议问题