實(shí)例屬性和類屬性
>>> class Student(object):
...? ? name = 'Student'
>>> s = Student() # 創(chuàng)建實(shí)例s
>>> print(s.name) # 打印name屬性,因?yàn)閷?shí)例并沒有name屬性催蝗,所以會繼續(xù)查找class的name屬性
Student
>>> print(Student.name) # 打印類的name屬性
Student
>>> s.name = 'Michael' # 給實(shí)例綁定name屬性
>>> print(s.name) # 由于實(shí)例屬性優(yōu)先級比類屬性高膘茎,因此肛走,它會屏蔽掉類的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__定義的屬性僅對當(dāng)前類實(shí)例起作用即寒,對繼承的子類是不起作用的橡淆,除非在子類中也定義__slots__,這樣母赵,子類實(shí)例允許定義的屬性就是自身的__slots__加上父類的__slots__逸爵。