python进阶17:__slots__
来源:互联网 发布:淘宝口令红包怎么领取 编辑:程序博客网 时间:2024/05/21 04:19
由于Python是动态语言,任何实例在运行期都可以动态地添加属性。如果要限制添加的属性,例如,Student类只
允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。顾名思义,
__slots__是指一个类允许的属性列表:
class Student(object): __slots__ = ('name', 'gender, 'score') def __init__(self, name, gender, score): self.name = name self.gender = gender self.score = score对实例进行操作:
>>> s = Student('Bob', 'male', 59)>>> s.name = 'Tim' #OK>>> s.score = 99 #OK>>> s.grade = 'A'Traceback (most recent call last): ...AttributeError: 'Student' object has no attribute 'grade'__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。
0 0
- python进阶17:__slots__
- 17 Python __slots__
- 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__ 作用
- 序列模式--双缓冲模式
- Maven最实用settings.xml
- CvMat、Mat、IplImage之间的转换详解及实例
- 88. Merge Sorted Array
- 菜鸟的Linux学习史——第一章 Linux和Unix之间的关系
- python进阶17:__slots__
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- linux+Vim
- 简单的数据结构——顺序表
- #define的用法及与typedef的区别
- 为什么现在大多数服务器使用linux系统区别的一些总结
- 十九、Hive日志分析案例一
- WinEdit初使用
- 避免“锤子”心理