使用slots
正常情況下,當(dāng)我們定義了一個(gè)class,創(chuàng)建了一個(gè)class的實(shí)例后,我們可以給該實(shí)例綁定任何屬性和方法,這就是動態(tài)語言的靈活性。
class Student(object):
pass
還可以嘗試給實(shí)例綁定一個(gè)方法:
>>> def set_age(self, age): # 定義一個(gè)函數(shù)作為實(shí)例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 給實(shí)例綁定一個(gè)方法
>>> s.set_age(25) # 調(diào)用實(shí)例方法
>>> s.age # 測試結(jié)果
25
但是,給一個(gè)實(shí)例綁定的方法,對另一個(gè)實(shí)例是不起作用的:
>>> s2 = Student() # 創(chuàng)建新的實(shí)例
>>> s2.set_age(25) # 嘗試調(diào)用方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'set_age'
為了給所有實(shí)例都綁定方法,可以給class綁定方法:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
給class綁定方法后,所有實(shí)例均可調(diào)用:
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
通常情況下,上面的set_score方法可以直接定義在class中,但動態(tài)綁定允許我們在程序運(yùn)行的過程中動態(tài)給class加上功能,這在靜態(tài)語言中很難實(shí)現(xiàn)。
但是,如果我們想要限制實(shí)例的屬性怎么辦?比如,只允許對Student實(shí)例添加name和age屬性。
為了達(dá)到限制的目的,Python允許在定義class的時(shí)候,定義一個(gè)特殊的__slots__變量,來限制該class實(shí)例能添加的屬性:
class Student(object):
__slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱
>>> s = Student() # 創(chuàng)建新的實(shí)例
>>> s.name = 'Michael' # 綁定屬性'name'
>>> s.age = 25 # 綁定屬性'age'
>>> s.score = 99 # 綁定屬性'score'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
由于'score'沒有被放到__slots__中,所以不能綁定score屬性,試圖綁定score將得到AttributeError的錯(cuò)誤。
__slots__定義的屬性僅對當(dāng)前類實(shí)例起作用,對繼承的子類是不起作用的
使用@property
Python內(nèi)置的@property(性能)裝飾器就是負(fù)責(zé)把一個(gè)方法變成屬性調(diào)用的。
class Student(object):
@property
def score(self):
return self._score # 一定要在score前面加下劃線 否則會出現(xiàn)下面情況
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('score must be a integer!')
if value < 0 or value > 100:
raise ValueError('score must beween 0 ~ 100!')
self._score = value
>>> s = Student()
>>> s.score = 60
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
s.score = 60
File "C:\Python36x32bit\practice.py", line 13, in score
self.score = value
File "C:\Python36x32bit\practice.py", line 13, in score
self.score = value
File "C:\Python36x32bit\practice.py", line 13, in score
self.score = value
[Previous line repeated 492 more times]
File "C:\Python36x32bit\practice.py", line 11, in score
if value < 0 or value > 100:
RecursionError: maximum recursion depth exceeded in comparison
注釋:
-
self.是對屬性的訪問,使用它的時(shí)候編譯器會判斷_是否為空,為空的話自動實(shí)例化。會自動訪問get和set方法。 -
_是對實(shí)例變量的訪問,我們沒有實(shí)例化它,不能使用。 - 對類里局部變量訪問使用
_,外部變量則用self.。 - 在
getter方法中,不要再使用self。否則會重復(fù)調(diào)用getter方法,造成死循環(huán)。
正常情況下,把一個(gè)getter方法變成屬性,只需要加上@property就可以了,此時(shí),@property本身又創(chuàng)建了另一個(gè)裝飾器@score.setter,負(fù)責(zé)把一個(gè)setter方法變成屬性賦值,于是,我們就擁有一個(gè)可控的屬性操作:
>>> s = Student()
>>> s.score = 60 # OK,實(shí)際轉(zhuǎn)化為s.set_score(60)
>>> s.score # OK,實(shí)際轉(zhuǎn)化為s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
還可以定義只讀屬性,只定義getter方法,不定義sette方法就是一個(gè)只讀屬性:
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self,value): #可讀寫屬性
self._birth = value
@property
def age(self): #只讀屬性, 因?yàn)閍ge可以根據(jù)birth和當(dāng)前時(shí)間計(jì)算出來
return 2018 - self._birth
>>> s = Student()
>>> s.birth = 1995
>>> s.age
23
>>> s.age = 24
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
s.age = 24
AttributeError: can't set attribute