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' 只读属性