http://www.2cto.com/kf/201412/359312.html
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
s1 = Student()
s1.name = "Lily"
s1.score = 9999 # 这里的定义是不合理的
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def get_score(self):
return self.score
def set_score(self,score):
if not isinstance(score, int):
raise ValueError("invalid score!!!")
if score < 0 or score > 100:
raise ValueError("score must be between [0,100]!!!")
self._score = score
s1 = Student()
s1.set_score(9999) #这里会抛出异常
class Student(object):
def __init__(self,name,score):
self._name = name
self._score = score
@property
def score(self):
return self._score
@score.setter
def score(self,score):
if not isinstance(score,int):
raise ValueError("invalid score!!!")
if score < 0 or score > 100:
raise ValueError("score must be between [0,100]!!!")
self._score = score
@property
def name(self):
return self._name
s1 = Student("Lily", 90)
s1.name = "Luly"
s1.score = 100
class Student(object):
def __init__(self,name,score):
self._name = name
self._score = score
@property
def AA(self):
return self._score
@AA.setter
def AA(self,score):
if not isinstance(score,int):
raise ValueError("invalid score!!!")
if score < 0 or score > 100:
raise ValueError("score must be between [0,100]!!!")
self._score = score
@property
def name(self):
return self._name
s1 = Student("Lily", 90)
s1.name = "Luly"
s1.AA = 100 # 这里相当于是 s1.AA(100)
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
@property
def score(self):
return self.score
@score.setter
def score(self,score):
if not isinstance(score,int):
raise ValueError("invalid score!!!")
if score < 0 or score > 100:
raise ValueError("score must be between [0,100]!!!")
self.score = score
@property
def name(self):
return self.name
def func(self):
self.score = score
s1 = Student("Lily", 90)
s1.func()
@property
def name(self):
return self.name