上邊的例子中,前三項(xiàng)都不符合,則直接使用默認(rèn)元類type。即上邊的語(yǔ)句相當(dāng)于:
def hello(self): print("hello world") returnFoo = type("Foo", (object,), {"hello": hello})
此時(shí)可以看出,實(shí)際上類Foo是元類type的實(shí)例。參見文章的封面圖。
3. 動(dòng)態(tài)創(chuàng)建類
Python中的類可以動(dòng)態(tài)創(chuàng)建,用的就是默認(rèn)元類type。動(dòng)態(tài)創(chuàng)建類的type函數(shù)原型為:
type(object_or_name, bases, dict)
這里不過多贅述,上個(gè)章節(jié)中有介紹。舉個(gè)比較復(fù)雜的動(dòng)態(tài)創(chuàng)建類的例子:
def init(self, name): self.name = namereturndef hello(self):print("hello %s" % self.name)returnFoo = type("Foo", (object,), {"__init__": init, "hello": hello, "cls_var": 10})foo = Foo(