先記錄一下代碼,后續(xù)補(bǔ)全學(xué)習(xí)體會。
1.使用slots
class Student(object): pass
s = Student() s.name='Michael' #動態(tài)給實(shí)例綁定一個屬性 print s.name
def set_age(self,age): #定義一個函數(shù)作為實(shí)例方法 self.age=age
from types import MethodType s.set_age=MethodType(set_age,s,Student) #給實(shí)例綁定一個方法 s.set_age(25) #調(diào)用實(shí)例方法 s.age #測試結(jié)果
s2=Student() #創(chuàng)建新的實(shí)例 s2.set_age(25) #嘗試調(diào)用方法
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() #創(chuàng)建新的實(shí)例 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