Python學習筆記3

來源:互聯網
上載者:User

標籤:

__slots__

如果我們想要限制class的屬性怎麼辦?比如,只允許對Student執行個體添加nameage屬性。

為了達到限制的目的,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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.