对于Python中@property的理解和使用

@property

这个我们在很多代码中都会用到,简单讲即为一个只读属性的调用

如果需要有修改权限,需要再加一个@属性名.setter

例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# @property 示例
class Student(object):
    @property
    def score(self):
        return self._score
    
    @score.setter
    def score(self, value):
        self._score = value
        
s = Student()
s.score = 3
print(s.score)

运行结果:

3

 

s.score=3类似于set_score(3)这样的设置值的功能

注意的是,如果没有@score.setter则表示为只读属性。

posted @ 2018-02-28 09:40  绿色的麦田  阅读(667)  评论(0编辑  收藏  举报