Python內建函數Type()函數一個有趣的用法

來源:互聯網
上載者:User
今天在網上看到type的一段代碼 ,然後查了一下文檔,才知道type還有三個參數的用法。

http://docs.python.org/2/library/functions.html#type

以前只是知道type可以檢測物件類型。然後發現了一個有趣的用法。

代碼如下:


def println(self):
a = 1 + 1

print “%s,%s” % (self.aa, a)

A = type(‘A',(),{‘aa':'print a', ‘println': println})

a = A()

type(a)
Out[11]: __main__.A

a.println()
print a,2


第一個參數是類的名字,第二個元組是父類,第三個是屬性。

哈哈,我覺得很好笑,雖然我函數裡邊第一個參數還是寫的self,但是如果寫一段代碼都用這種方法定義類,然後再不注意類名的規範,代碼會變的很難讀。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.