小白學python之使用__slots__學習筆記

本文以廖雪峯的官方網站爲參考來學習python的。其學習鏈接爲廖雪峯小白學python教程

本文是學習到python的實例屬性和類屬性。參考鏈接廖雪峯python使用__slot__

嘗試給實例綁定一個屬性:

class Student(object):
    pass
s = Student()
s.name = 'Michael'
print(s.name)

運行結果: Michael

嘗試給實例綁定一個方法:

def set_age(self, age):
    self.age = age

from types import MethodType
s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)

運行結果: 25

 

筆記

給一個實例綁定的方法,對另一個實例是不起作用的:

s2 = Student()
s2.set_age(25)

運行結果,報錯:

Traceback (most recent call last):
  File "**********", line **, in <module>
    s2.set_age(25)
AttributeError: 'Student' object has no attribute 'set_age'

def set_score(self, score):
    self.score = score

Student.set_score= set_score
s.set_score(100)
print(s.score)

s2.set_score(99)
print(s2.score)

筆記

給class綁定方法後,所有實例均可調用。

通常情況下,上面的set_score方法可以直接調用在class中。但動態綁定允許我們在程序運行過程中動態給class加上功能,這在靜態語言中很難實現。

使用__slot__

class Student(object):
    __slots__=('name','age')
s = Student()
s.name = 'Michael'
s.age = 25
#print(s.name,s.age)
s.score = 99

運行結果,報錯:

Traceback (most recent call last):
  File "*********", line ***, in <module>
    s.score = 99
AttributeError: 'Student' object has no attribute 'score'

筆記

Python允許在定義class的時候,定義一個特殊的__slots__變量,來限制該class實例能添加的屬性。

__slots__定義的屬性僅對當前類實例起作用,對繼承的子類是不起作用的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章