您的位置:首页 > 编程语言 > Python开发

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:只读
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: