使用反射进行对象的展示设置(性能和可读性都更好)
1 class Shift: 2 show = 'output' 3 4 def __init__(self, line=1, uph=450, eff=1, wt=10): 5 self.uph = uph 6 self.eff = eff 7 self.wt = wt 8 self.line = line 9 10 @property 11 def output(self): 12 return self.uph * self.eff * self.wt 13 14 def __repr__(self): 15 return f'{getattr(self, self.show)}'
使用类字典存储匿名函数进行对象的展示设置
1 class Shift: 2 show = 'output' 3 attr_mapping = { 4 'output': lambda self: self.output, 5 'uph': lambda self: self.uph, 6 'eff': lambda self: self.eff, 7 'wt': lambda self: self.wt, 8 } 9 def __init__(self, line=1, uph=450, eff=1, wt=10): 10 self.uph = uph 11 self.eff = eff 12 self.wt = wt 13 self.line = line 14 @property 15 def output(self): 16 return self.uph * self.eff * self.wt 17 18 def __repr__(self): 19 return f'{self.attr_mapping.get(self.show)(self)}'