python基础——使用__slots__
?
python基礎(chǔ)——使用__slots__
正常情況下,當(dāng)我們定義了一個(gè)class,創(chuàng)建了一個(gè)class的實(shí)例后,我們可以給該實(shí)例綁定任何屬性和方法,這就是動(dòng)態(tài)語(yǔ)言的靈活性。先定義class:
class Student(object):pass然后,嘗試給實(shí)例綁定一個(gè)屬性:
>>> s = Student() >>> s.name = 'Michael' # 動(dòng)態(tài)給實(shí)例綁定一個(gè)屬性 >>> print(s.name) Michael還可以嘗試給實(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 # 測(cè)試結(jié)果 25但是,給一個(gè)實(shí)例綁定的方法,對(duì)另一個(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中,但動(dòng)態(tài)綁定允許我們?cè)诔绦蜻\(yùn)行的過程中動(dòng)態(tài)給class加上功能,這在靜態(tài)語(yǔ)言中很難實(shí)現(xiàn)。
?
使用__slots__
但是,如果我們想要限制實(shí)例的屬性怎么辦?比如,只允許對(duì)Student實(shí)例添加name和age屬性。
為了達(dá)到限制的目的,Python允許在定義class的時(shí)候,定義一個(gè)特殊的__slots__變量,來限制該class實(shí)例能添加的屬性:
class Student(object):__slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱然后,我們?cè)囋?#xff1a;
>>> 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__要注意,__slots__定義的屬性僅對(duì)當(dāng)前類實(shí)例起作用,對(duì)繼承的子類是不起作用的:
>>> class GraduateStudent(Student): ... pass ... >>> g = GraduateStudent() >>> g.score = 9999除非在子類中也定義__slots__,這樣,子類實(shí)例允許定義的屬性就是自身的__slots__加上父類的__slots__。
?
參考源碼:
#python 使用__slots__ 示例 #2016-8-29 21:25:14 #MengmengCoding # -*- coding: utf-8 -*-#使用__slots__限制實(shí)例的屬性class Student(object):__slots__=('name','age') #用tuple定義允許綁定的屬性名稱#新類,繼承于Student class GraduateStudent(Student):passs=Student() #創(chuàng)建新的實(shí)例 s.name='Shuke' #綁定屬性'name' s.age=25 #綁定屬性'age'# ERROR: AttributeError: 'Student' object has no attribute 'score' try:s.score=99 except AttributeError as e:print('AttributeError:',e)g=GraduateStudent() #創(chuàng)建新的實(shí)例 ''' 使用__slots__要注意,__slots__定義的屬性僅對(duì)當(dāng)前類實(shí)例起作用, 對(duì)繼承的子類是不起作用的 ''' g.score=99 #綁定屬性'score' print('g.score=',g.score)?
轉(zhuǎn)載于:https://www.cnblogs.com/codingmengmeng/p/5819891.html
總結(jié)
以上是生活随笔為你收集整理的python基础——使用__slots__的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小甲鱼python视频第八讲(课后习题)
- 下一篇: websocket python爬虫_p