【python】__slots__简介
来源:互联网 发布:nginx配置地址转发 编辑:程序博客网 时间:2024/05/30 04:30
__slots__ 呢是为了来限制class属性的,我们知道,当我们创建一个实例的时候可以来给他增加一些属性或者方法,但是如果我们想要限制class的属性,只允许它有特定的属性的时候就用到__slots__ 了。
举例说明:
class Student(object): __slots__ = ('name', 'age')#用tuple定义允许绑定的属性名称
这样我们就只能使用name 和age属性了
>>> s = Student() # 创建新的实例>>> s.name = 'Michael' # 绑定属性'name'>>> s.age = 25 # 绑定属性'age'>>> s.score = 99 # 绑定属性'score'Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute 'score'
注意⚠️
这个只有在本类中有效,如果他作为父类的话,那么子类用的时候不会有此限制,如果想让子类有此限制,那么就需要在子类中重新定义。那么子类中允许定义的属性就是子类的加上父类的。
0 0
- 【python】__slots__简介
- python __slots__
- python __slots__
- Python __slots__
- Python---__slots__
- python __slots__
- python __slots__ 使用
- python的__slots__
- python使用__slots__
- python class __slots__
- python的__slots__
- python __slots__方法
- Python的__slots__
- Python的__slots__
- Python @property __slots__
- Python __slots__ 作用
- python中 __slots__
- 17 Python __slots__
- 在RHEL7或者OL7上安装11.2.0.4的GI时需要特别注意的问题
- C++读书笔记3:继承与多态
- Tornado 多进程实现分析
- 投资人豪赌 共享单车吸金超10亿
- 我为什么还在做投资?
- 【python】__slots__简介
- 对话淡马锡主席林文兴,柳传志谈多元布局动态优化!
- JAVA设计模式是个什么玩意儿_03_单例模式
- Webservice----axis2
- 中国商务旅行开支持续增长,企业开始采用以员工为中心的差旅项目
- C++读书笔记5:标准模板库
- 项目管理初体验
- Mac配置openvpn服务端和客户端
- ubuntu 安装openssh服务