python中class 的一行式构造器
2016-06-13 09:17
323 查看
好处:避免类初始化时大量重复的赋值语句
用到了魔法__dict__
用到了魔法__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()
相关文章推荐
- python入门简章
- Python处理带timezone的datetime类型
- 欢迎使用CSDN-markdown编辑器
- python中简单的类定义及调用方法
- 使用Python处理目录(一):打印目录下的文件名
- Python __file__与argv[0]
- python的函数定义方式
- Python中进行布尔类型处理时的特殊点
- numpy中的ndarray方法和属性
- python的print函数的一些功能
- Python环境安装
- 22.python中的面向对象和类的基本语法
- 学习Python(1) —— Python运行环境安装
- python数值范围内的迭代
- 树莓派lasersensor(Python程序)
- python的for语句的输出格式的改变
- python中的while和for语句的简单使用
- Python数字
- 简单的启程,从这里开始
- python的if语句