Python: Quick and dirty datatypes (DTO)

后端 未结 6 1760
孤城傲影
孤城傲影 2021-02-12 10:22

Very often, I find myself coding trivial datatypes like

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


        
6条回答
  •  攒了一身酷
    2021-02-12 10:56

    Are there any popular idioms in python to derive quick ... datatypes with named accessors?

    Dataclases. They accomplish this exact need.

    Some answers have mentioned dataclasses, but here is an example.

    Code

    import dataclasses as dc
    
    
    @dc.dataclass(unsafe_hash=True)
    class Pruefer:
        ident : int
        maxnum : float = float("inf")
        name : str  = ""
    

    Demo

    pr = Pruefer(1, 2.0, "3")
    
    pr
    # Pruefer(ident=1, maxnum=2.0, name='3')
    
    pr.ident
    # 1
    
    pr.maxnum
    # 2.0
    
    pr.name
    # '3'
    
    hash(pr)
    # -5655986875063568239
    

    Details

    You get:

    • pretty reprs
    • default values
    • hashing
    • dotted attribute-access
    • ... much more

    You don't (directly) get:

    • tuple unpacking (unlike namedtuple)

    Here's a guide on the details of dataclasses.

提交回复
热议问题