標籤:
__slots__
如果我們想要限制class的屬性怎麼辦?比如,只允許對Student執行個體添加name和age屬性。
為了達到限制的目的,Python允許在定義class的時候,定義一個特殊的__slots__變數,來限制該class能添加的屬性:
>>> class Student(object):... __slots__ = (‘name‘, ‘age‘) # 用tuple定義允許綁定的屬性名稱...
然後,我們試試:
>>> s = Student() # 建立新的執行個體>>> 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的錯誤。
使用__slots__要注意,__slots__定義的屬性僅對當前類起作用,對繼承的子類是不起作用的:
>>> class GraduateStudent(Student):... pass...>>> g = GraduateStudent()>>> g.score = 9999
除非在子類中也定義__slots__,這樣,子類允許定義的屬性就是自身的__slots__加上父類的__slots__。
__str__
我們先定義一個Student類,列印一個執行個體:
>>> class Student(object):... def __init__(self, name):... self.name = name...>>> print Student(‘Michael‘)<__main__.Student object at 0x109afb190>
列印出一堆<__main__.Student object at 0x109afb190>,不好看。
怎麼才能列印得好看呢?只需要定義好__str__()方法,返回一個好看的字串就可以了:
>>> class Student(object):... def __init__(self, name):... self.name = name... def __str__(self):... return ‘Student object (name: %s)‘ % self.name...>>> print Student(‘Michael‘)Student object (name: Michael)
這樣列印出來的執行個體,不但好看,而且容易看出執行個體內部重要的資料。
但是細心的朋友會發現直接敲變數不用print,列印出來的執行個體還是不好看:
>>> s = Student(‘Michael‘)>>> s<__main__.Student object at 0x109afb310>
這是因為直接顯示變數調用的不是__str__(),而是__repr__(),兩者的區別是__str__()返回使用者看到的字串,而__repr__()返回程式開發人員看到的字串,也就是說,__repr__()是為調試服務的。
解決辦法是再定義一個__repr__()。但是通常__str__()和__repr__()代碼都是一樣的,所以,有個偷懶的寫法:
class Student(object): def __init__(self, name): self.name = name def __str__(self): return ‘Student object (name=%s)‘ % self.name __repr__ = __str__
Python學習筆記3