Why does Python not support record type? (i.e. mutable namedtuple)

后端 未结 11 1564
眼角桃花
眼角桃花 2020-12-12 22:10

Why does Python not support a record type natively? It\'s a matter of having a mutable version of namedtuple.

I could use namedtuple._replace. But I nee

11条回答
  •  一整个雨季
    2020-12-12 22:26

    As tzot stated, since Python ≥3.3, Python does have a mutable version of namedtuple: types.SimpleNamespace.

    These things are very similar to the new C# 9 Records.

    Here are some usage examples:

    Positional constructor arguments

    >>> import types
    >>>
    >>> class Location(types.SimpleNamespace):
    ...   def __init__(self, lat=0, long=0):
    ...     super().__init__(lat=lat, long=long)
    ...
    >>> loc_1 = Location(49.4, 8.7)
    

    Pretty repr

    >>> loc_1
    Location(lat=49.4, long=8.7)
    

    Mutable

    >>> loc_2 = Location()
    >>> loc_2
    Location(lat=0, long=0)
    >>> loc_2.lat = 49.4
    >>> loc_2
    Location(lat=49.4, long=0)
    

    Value semantics for equality

    >>> loc_2 == loc_1
    False
    >>> loc_2.long = 8.7
    >>> loc_2 == loc_1
    True
    

    Can add attributes at runtime

    >>> loc_2.city = 'Heidelberg'
    >>> loc_2
    

提交回复
热议问题