@property使用

# coding:utf-8
"""
property:负责把方法变成属性
"""

class Student(object):

    def get_score(self):
        return self._score

    def set_score(self, score):
        if not isinstance(score, int):
            raise ValueError('score must be an instance!')
        if score<0 or score>100:
            raise ValueError('score must between 0--100!')
        self._score = score

s =Student()
s.set_score(60)
print s.get_score()

#s.set_score(200)

"""
下面的方法既能检查参数,又可以用类似属性这样简单的方式来访问类的变量
把一个getter方法变成属性,只需要加上@property.
此时@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
"""
class Student2(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, score):
        if not isinstance(score, int):
            raise ValueError('score must be an instance!')
        if score<0 or score>100:
            raise ValueError('score must between 0--100!')
        self._score = score

s = Student2()
s.score =50
print s.score
#s.score = 120

"""
利用@property定义只读属性,只定义getattr,不定义setattr即可
"""
class Student3(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self,value):
        self._birth = value

    @property
    def age(self):
        return 2016 -  self._birth

s = Student3()
s.birth = 1988
print s.birth
print s.age

 

posted @ 2016-03-19 19:37  jetlyb  阅读(196)  评论(0编辑  收藏  举报