避免在每新建类时,都要重复实现构造器,因此可以定义一个公共基类,在基类中实现实例属性的初始化规则,此后在派生类中,只需要指定属性字段即可
1 class Init: 2 _fields = [] 3 4 def __init__(self, *args, **kwargs): 5 if len(args) > len(self._fields): 6 raise TypeError 7 for k, v in zip(self._fields, args): 8 setattr(self, k, v) 9 for k in self._fields[len(args):]: 10 setattr(self, k, kwargs.pop(k)) 11 if len(kwargs): 12 raise TypeError 13 14 15 class Valley(Init): 16 _fields = ["姓名", "年纪"] 17 18 19 v = Valley("shixiaogu", 年纪=25) 20 print(v.__dict__)标签:__,初始化,fields,self,args,len,简化,._,数据结构 From: https://www.cnblogs.com/shixiaogu/p/16722795.html