Python: Quick and dirty datatypes (DTO)

后端 未结 6 1862
后悔当初
后悔当初 2021-02-12 10:21

Very often, I find myself coding trivial datatypes like

class Pruefer:
    def __init__(self, ident, maxNum=float(\'inf\')         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-12 10:49

    >>> from collections import namedtuple
    >>> Pruefer = namedtuple("Pruefer", "ident maxNum name")
    >>> pr = Pruefer(1,2,3)
    >>> pr.ident
    1
    >>> pr.maxNum
    2
    >>> pr.name
    3
    >>> hash(pr)
    2528502973977326415
    

    To provide default values, you need to do little bit more... Simple solution is to write subclass with redefinition for __new__ method:

    >>> class Pruefer(namedtuple("Pruefer", "ident maxNum name")):
    ...     def __new__(cls, ident, maxNum=float('inf'), name=""):
    ...         return super(Pruefer, cls).__new__(cls, ident, maxNum, name)
    ... 
    >>> Pruefer(1)
    Pruefer(ident=1, maxNum=inf, name='')
    

提交回复
热议问题