Python: Quick and dirty datatypes (DTO)

后端 未结 6 1861
后悔当初
后悔当初 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:43

    An alternate approach which might help you to make your boiler plate code a little more generic is the iteration over the (local) variable dicts. This enables you to put your variables in a list and the processing of these in a loop. E.g:

    class Pruefer:
         def __init__(self, ident, maxNum=float('inf'), name=""):
             for n in "ident maxNum name".split():
                 v = locals()[n]  # extract value from local variables
                 setattr(self, n, v)  # set member variable
    
         def printMemberVars(self):
             print("Member variables are:")
             for k,v in vars(self).items():
                 print("  {}: '{}'".format(k, v))
    
    
    P = Pruefer("Id", 100, "John")
    P.printMemberVars()
    

    gives:

    Member Variables are:
      ident: 'Id'
      maxNum: '100'
      name: 'John'
    

    From the viewpoint of efficient resource usage, this approach is of course suboptimal.

提交回复
热议问题