码迷,mamicode.com
首页 > 其他好文 > 详细

@property使用

时间:2016-03-19 20:57:15      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

# 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

 

@property使用

标签:

原文地址:http://www.cnblogs.com/ponyliu/p/5296082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!