雖然Python本身很難說(shuō)是面向?qū)ο笳Z(yǔ)言,但Python中的數(shù)據(jù)模型( data model
)可以說(shuō)真的是“純面向?qū)ο?rdquo;。在Python的世界里,一切皆是對(duì)象。無(wú)論是數(shù)值、字符串、序列、字典、函數(shù)、模塊、類、實(shí)例、文件等等。
元類(metaclass)是Python 2.2中引入的概念,它的作用是定制類的創(chuàng)建行為。這么解釋可能有點(diǎn)難理解,那么這篇文章就通過(guò)實(shí)例,一步步解釋Python中的元類。
1. Python中一切皆對(duì)象,包括類
class Foo:def hello(self):print("hello world!")returnfoo = Foo()print(type(foo)) # <class '__main__.Foo'>print(type(foo.hello)) # <class 'method'>print(type(Foo)) # <class 'type'>temp = Foo # 賦值給其他變量Foo.var = 11 # 增加參數(shù)print(Foo) # 作為函數(shù)參數(shù)
例子中type(Foo)說(shuō)明Foo本身也是一個(gè)對(duì)象,可以將其賦值給其他對(duì)象、對(duì)其添加屬性、將其作為函數(shù)參數(shù)傳遞等等。
2. 類的創(chuàng)建過(guò)程
在上邊的例子中,類Foo的創(chuàng)建過(guò)程中會(huì)執(zhí)行class語(yǔ)句,此時(shí)需要首先確定元類(元類定制類的創(chuàng)建行為)。元類的確定過(guò)程如下: