好处:避免类初始化时大量重复的赋值语句

 

用到了魔法__dict__

 

# 一行式构造器

class Test():
    # 初始化
    def __init__(self, a, b, c=2, d=3, e=4, f=5):
        self.__dict__.update({k:v for k,v in locals().items() if k != 'self'})
    
    # 设置
    def set_option(self, *args, **kwargs):
        self.__dict__.update(dict(zip('abcdef'[:len(args)], args))) # args 必须按__init__的顺序!
        self.__dict__.update(kwargs)
        
    # 别的方法
    def show(self):
        print(self.__dict__)
    
    
t = Test(0, 1)
t.show()
t.set_option(100, 99, 98, 97, f=96, e=95)
t.show()

 

相关文章:

  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2021-07-31
  • 2022-12-23
  • 2022-01-18
  • 2021-07-14
  • 2022-12-23
猜你喜欢
  • 2021-10-10
  • 2021-09-13
  • 2022-12-23
  • 2021-11-04
  • 2021-05-18
  • 2022-02-26
相关资源
相似解决方案