关于 python 的 @property总结和思考

其实关于@property我到处去搜了很多教程来看,因为公司大量使用了oop的编程而我以前很少写,所以现在来重新补过来。

从使用上来说 加了@property之后最明显的区别就是 

 class Student(object):

    def get_score(self):
        return self._score

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

#实例化Student类
x = Student()

#调用get_score方法
x.get_score()

然而如果你加上了@property
那么x.get_score 就可以运行了

这可能是我最明显最直观对 @property的感受。

其他的在使用@property之后还有很多特性都可以使用了

详情参考http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820062641f3bcc60a4b164f8d91df476445697b9e000

廖雪峰 老师的教程。

原文地址:https://www.cnblogs.com/piperck/p/5008002.html