python class __slots__
2015-07-27 14:00
537 查看
1,由于Python是动态语言,任何实例在运行过程中,都可以动态地添加属性,python中通过slots 来限制添加属性。
如下代码:
slots 的目的是限制当前类所拥有的属性。
对于继承类的限制属性添加如下:
如下代码:
class Student(objetc): __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 的目的是限制当前类所拥有的属性。
对于继承类的限制属性添加如下:
class Person(object): __slots__ = ('name', 'gender') def __init__(self, name, gender): self.name = name self.gender = gender class Student(Person): __slots__ = ('score',) def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score
相关文章推荐
- Logistic回归python代码
- Python正则表达式的七个使用范例
- python 链接hive
- 利用hadoop+hive+python+qqwry.dat批量解析ip物理地址
- window7 64位 python2.7 安装libsvm和liblinear
- Python @property
- python基础教程总结15——2 画幅好画
- Python修饰器的函数式编程
- python-influxdb
- Python开发入门与实战12-业务逻辑层
- Python入门笔记(18):Python函数(1):基础部分
- python笔记002
- python2.7下安装PIL库
- 转载:python super()及相关引申
- Python中map()函数
- 命令行2048
- Windows下Python包和模块的安装方法
- 正则
- Sublime2下配置Python模块查找路径PYTHONPATH
- Python—global vs local variables