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

后端 未结 11 1565
眼角桃花
眼角桃花 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:33

    Python <3.3

    You mean something like this?

    class Record(object):
        __slots__= "attribute1", "attribute2", "attribute3",
    
        def items(self):
            "dict style items"
            return [
                (field_name, getattr(self, field_name))
                for field_name in self.__slots__]
    
        def __iter__(self):
            "iterate over fields tuple/list style"
            for field_name in self.__slots__:
                yield getattr(self, field_name)
    
        def __getitem__(self, index):
            "tuple/list style getitem"
            return getattr(self, self.__slots__[index])
    
    >>> r= Record()
    >>> r.attribute1= "hello"
    >>> r.attribute2= "there"
    >>> r.attribute3= 3.14
    
    >>> print r.items()
    [('attribute1', 'hello'), ('attribute2', 'there'), ('attribute3', 3.1400000000000001)]
    >>> print tuple(r)
    ('hello', 'there', 3.1400000000000001)
    

    Note that the methods provided are just a sample of possible methods.

    Python ≥3.3 update

    You can use types.SimpleNamespace:

    >>> import types
    >>> r= types.SimpleNamespace()
    >>> r.attribute1= "hello"
    >>> r.attribute2= "there"
    >>> r.attribute3= 3.14
    

    dir(r) would provide you with the attribute names (filtering out all .startswith("__"), of course).

提交回复
热议问题