首页 > 编程语言 > 详细

python类中property的使用

时间:2021-02-09 18:01:11      阅读:16      评论:0      收藏:0      [点我收藏+]

1. 要解决的问题: 想要快速的访问类中的私有属性,但是不想直接暴露出原来类中的属性

@property    

def tick(self):

  return self._tick

 

2. 经典例子

# property decorator make defining and modifying class‘s property easy
class Student:
    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, score):
        if isinstance(score, int):
            self.__score = score
        else:
            print(score must be int)


if __name__ == __main__:
    s = Student()
    s.score = a‘  # 直接使用类的方法名字, 而不是直接使用类的属性
    print(s.score)

 

3.  直接使用类的方法名字, 而不是直接使用类的属性

class Student:
    def __init__(self, score):
        self._score = score

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


if __name__ == __main__:
    s = Student(5)
    print(s.return_score)

参考: https://www.cnblogs.com/linuxchao/p/linuxchao-property.html

python类中property的使用

原文:https://www.cnblogs.com/hixiaowei/p/14392671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!