先记录一下代码,后续补全学习体会。
1.使用slots
class Student(object): pass
s = Student() s.name='Michael' #动态给实例绑定一个属性 print s.name
def set_age(self,age): #定义一个函数作为实例方法 self.age=age
from types import MethodType s.set_age=MethodType(set_age,s,Student) #给实例绑定一个方法 s.set_age(25) #调用实例方法 s.age #测试结果
s2=Student() #创建新的实例 s2.set_age(25) #尝试调用方法
def set_score(self,score): self.score=score Student.set_score=MethodType(set_score,None,Student) s.set_score(100) s.score s2.set_score(99) s2.score
class Student(object): __slots__=('name','age') #用tuple定义允许绑定的属性名称 s=Student() #创建新的实例 s.name='Micheal' #绑定属性name s.age=25 # 绑定属性age s.score=99 #绑定属性score
class GraduateStudent(Student): pass g=GraduateStudent() g.score=9999
2.使用@property
code_snap_1:
class Student(object): 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() s.set_score(60) s.get_score() s.set_score(9999)
code_snap_2:
class Student(object): @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() s.score=60 s.score s.score=9999
code_snap_3:
class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self,value): self._birth=value @property def age(self): return 2014-self.birth s=Student() s.birth=1988 s.age
网友评论