實(shí)例屬性和類屬性
>>> class Student(object):
...? ? name = 'Student'
>>> s = Student() # 創(chuàng)建實(shí)例s
>>> print(s.name) # 打印name屬性,因?yàn)閷?shí)例并沒有name屬性,所以會(huì)繼續(xù)查找class的name屬性
Student
>>> print(Student.name) # 打印類的name屬性
Student
>>> s.name = 'Michael' # 給實(shí)例綁定name屬性
>>> print(s.name) # 由于實(shí)例屬性優(yōu)先級(jí)比類屬性高,因此,它會(huì)屏蔽掉類的name屬性
Michael
>>> print(Student.name) # 但是類屬性并未消失,用Student.name仍然可以訪問
Student
>>> del s.name # 如果刪除實(shí)例的name屬性
>>> print(s.name) # 再次調(diào)用s.name,由于實(shí)例的name屬性沒有找到,類的name屬性就顯示出來了
Student
在編寫程序的時(shí)候,千萬不要把實(shí)例屬性和類屬性使用相同的名字,因?yàn)橄嗤Q的實(shí)例屬性將屏蔽掉類屬性,但是當(dāng)你刪除實(shí)例屬性后,再使用相同的名稱,訪問到的將是類屬性。
使用__slots__
為了給所有實(shí)例都綁定方法,可以給class綁定方法
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 "", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
使用__slots__要注意,__slots__定義的屬性僅對(duì)當(dāng)前類實(shí)例起作用,對(duì)繼承的子類是不起作用的,除非在子類中也定義__slots__,這樣,子類實(shí)例允許定義的屬性就是自身的__slots__加上父類的__slots__。