Python 面向对象 —— __slots__ 与 @property(python 下的 getter、setter 方法)
2016-05-25 10:19
633 查看
1. 使用 __slots__ 限制 class 的属性
class Student(object): __slots__ = {'name', 'age'} # 集合 # 也只允许绑定 name,age 这两个属性 # 如果有新的属性想要帮顶,则会抛出 AttributeError
(1)
__slots__:定义的属性仅对当前类起作用,对继承的子类不起作用
(2)除非在子类也定义
__slots__,子类允许定义的属性就是自身的
__slots__并上 父类的
__slots__
2. @property:作为属性的方法
class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise TypeError() if value < 0 or value > 100: raise ValueError() self._score = value
(1)@property:讲成员函数作为成员变量使用,含义为 getter
(2)@.setter:执行真正的类型检查
class Person(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): if not isinstance(value, int): raise TypeError() if value < 0: raise ValueError() self._birth = value @property def age(self): return 2016 - self._birth
(1)birth:可读写
(2)age:只读
相关文章推荐
- python 爬虫登陆学校教务系统
- Python Machine Learning---scikit-learn
- 350. Intersection of Two Arrays II [easy] (Python)
- 你可能不知道的30个Python语言的特点技巧
- python中的model模板中的数据类型
- python玩转大数据-(一)
- Python+Scrapy安装
- Python参数传递 - 引用传递&值传递
- 利用python快速实现不同机器间文件夹共享
- python packages
- python np.linspace
- 一台电脑同时安装不同的python、django版本
- Python学习笔记-day0
- python实例
- Python的re模块正则表达式操作
- python learning_curve函数
- 调整python默认递归深度
- python 检测代码性能
- python中的深拷贝和浅拷贝理解
- 入门超简单python入门神图