Python基础-@property

来源:互联网 发布:什么叫编程 编辑:程序博客网 时间:2024/05/29 03:08

@property

@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。

示例代码

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 使用@property# 颜值计算器class BeautifulValue(object):    @property    def score(self):        return self._value    # 这里相当于score函数的数值检测器,且名称要保持一致    @score.setter    def score(self, value):        if not isinstance(value, int):            raise ValueError("must be integer data")        if (value < 0) or (value > 10):            raise ValueError("must between 0 ~ 10")        self._value = valuedef testRun():    b = BeautifulValue();    b.score = 8    b.score = -1    #b.score = 100testRun()

运行结果

ValueError: must between 0 ~ 10

D:\PythonProject\sustudy>python main.pyTraceback (most recent call last):  File "main.py", line 29, in <module>    testRun()  File "main.py", line 26, in testRun    b.score = -1  File "main.py", line 18, in score    raise ValueError("must between 0 ~ 10")ValueError: must between 0 ~ 10
原创粉丝点击