Existence of mutable named tuple in Python?

前端 未结 10 2158
旧巷少年郎
旧巷少年郎 2020-11-29 16:23

Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects?

Primarily for readability, I would like something similar to namedt

10条回答
  •  既然无缘
    2020-11-29 17:09

    As a very Pythonic alternative for this task, since Python-3.7, you can use dataclasses module that not only behaves like a mutable NamedTuple because they use normal class definitions they also support other classes features.

    From PEP-0557:

    Although they use a very different mechanism, Data Classes can be thought of as "mutable namedtuples with defaults". Because Data Classes use normal class definition syntax, you are free to use inheritance, metaclasses, docstrings, user-defined methods, class factories, and other Python class features.

    A class decorator is provided which inspects a class definition for variables with type annotations as defined in PEP 526, "Syntax for Variable Annotations". In this document, such variables are called fields. Using these fields, the decorator adds generated method definitions to the class to support instance initialization, a repr, comparison methods, and optionally other methods as described in the Specification section. Such a class is called a Data Class, but there's really nothing special about the class: the decorator adds generated methods to the class and returns the same class it was given.

    This feature is introduced in PEP-0557 that you can read about it in more details on provided documentation link.

    Example:

    In [20]: from dataclasses import dataclass
    
    In [21]: @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
        ...:    
    

    Demo:

    In [23]: II = InventoryItem('bisc', 2000)
    
    In [24]: II
    Out[24]: InventoryItem(name='bisc', unit_price=2000, quantity_on_hand=0)
    
    In [25]: II.name = 'choco'
    
    In [26]: II.name
    Out[26]: 'choco'
    
    In [27]: 
    
    In [27]: II.unit_price *= 3
    
    In [28]: II.unit_price
    Out[28]: 6000
    
    In [29]: II
    Out[29]: InventoryItem(name='choco', unit_price=6000, quantity_on_hand=0)
    

提交回复
热议问题