python限定类属性的类属性:__slots__
2016-08-21 19:57
295 查看
__slots__ 由于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__也能节省内存。
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 s = Student('Bob', 'male', 59) s.name = 'Tim' s.score = 99 print s.score
相关文章推荐
- Python中的__SLOTS__属性使用示例
- Python属性、方法和类管理系列之----__slots__属性
- python 详解类class的通过__slots__限制类实例对象的属性(七)
- Python tricks(7) -- new-style class的__slots__属性
- 【python】详解类class的通过__slots__限制类实例对象的属性(七)
- __slots__ Python Class限制添加属性
- [Dynamic Language] Python __slots__ 限制绑定属性
- python----slots属性安全类
- python语言是动态语言、给类添加属性、方法、静态方法和类方法、__slots__()、python中的生成器、yield的用法
- python语言是动态语言、给类添加属性、方法、静态方法和类方法、__slots__()、python中的生成器、yield的用法
- Python实例属性限制(__slots__)
- python属性限制 __slots__
- Python中的__SLOTS__属性使用示例
- Python学习笔记 __slots__ 限制类属性
- Python3学习(23)--__slots__ 限制实例属性的绑定
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- Python----__slots__ 一个类允许的属性列表
- Python中__slots__属性介绍与基本使用方法
- 7 python 动态绑定,@property的使用__slots_限制class的属性以及多重继承
- python 类的__slots__属性