好处:避免类初始化时大量重复的赋值语句
用到了魔法__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()
转载于:https://www.cnblogs.com/hhh5460/p/5579478.html
相关资源:JAVA上百实例源码以及开源项目