python基础 -- property

1. 作用

把函数变成属性,同时可以对属性进行检查

2. 操作

# property
# getter, setter

# 设定属性
# 一般情况
# class Student(object):

#     def __init__(self, name, score):
#         self.__name = name  # __value 私有变量
#         self.__score = score # 不要在外部访问,don't do that

#     def get_name(self):
#         return self.__name

#     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

# s = Student('Tommy', 76)
# print('{}-{}'.format(s.get_name(), s.get_score()))
# s.set_score(90)
# print('{}-{}'.format(s.get_name(), s.get_score()))

# 加上property
# score()方法变成属性

class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    @property
    def name(self):
        return self.__name

    @property
    def score(self):
        return self.__score
    
    @score.setter
    def 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

s = Student('Tommy', 76)
print('{}-{}'.format(s.name, s.score))
s.score = 90
print('{}-{}'.format(s.name, s.score))
# s.name = 'Laura' 只读属性
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,195评论 0 13
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,615评论 0 5
  • 可以添加VIP Iphone上也可以添加 可以设置规则 比如重要的邮件红色显示。手机上无效 可以设置智能邮箱 参考...
    鸭梨山大哎阅读 289评论 0 1
  • 考研暑假班开课以来难得能中午在宿舍睡个午觉,一觉醒来已经是下午四点…感觉做了很长的梦。梦里光怪陆离,像是为了救谁而...
    传说头发软的人温柔阅读 193评论 0 0