使用type創(chuàng)建帶有屬性的類
type接受一個(gè)字典來為類定義屬性,因此
>>>Foo=type('Foo',(),{'bar':True})
可以翻譯為:
>>>class Foo(object):
... bar=True
并且可以將FOO當(dāng)成一個(gè)普通的類一樣使用:
>>>print (Foo)
<class '__main__.Foo'>
>>>print(Foo.bar)
True
>>>f=Foo()
>>>print(f)
<__main__.Foo object at 0x8a9b84c>
>>>print(f.bar)
True
當(dāng)然,你可以向這個(gè)類繼承,所以,如下的代碼:
>>>class FooChild(Foo):
... pass
就可以寫成:
>>>FooChild=type('FooChild',(Foo,),{})
>>>print(FooChild)
<class '__main__.FooChild'>
>>>print(FooChild.bar) #bar屬性是由Foo繼承而來
注意:
type的第二個(gè)參數(shù),元組中是父類的名字,而不是字符串
添加的屬性是類屬性,并不是實(shí)例屬性
使用type創(chuàng)建帶有方法的類
類增加方法,只需要定義一個(gè)帶有恰當(dāng)簽名的函數(shù)并將其作為屬性賦值即可
添加實(shí)例方法
>>>def echo_bar(self): #定義了一個(gè)普通函數(shù)
... print(self.bar)
>>>FooChild=type('FooChild',(Foo,),{'echo_bar':echo_bar})
#FooChild類中的echo_bar屬性,指向了上面定義的函數(shù)
>>>hasattr(Foo,'echo_bar') #判斷Foo類中,是否有echo_bar這個(gè)屬性
>>>False
>>>hassattr(FooChild,'echo_bar') #判斷FooChild類中,是否有echo_bar這個(gè)屬性
>>>True
>>>my_foo=FooChild()
>>>my_foo.echo_bar()
True
添加靜態(tài)方法
>>>@staticmethod
... def testStatic():
... print("static method...")
>>>Foochild=type('Foochild',(Foo,),{"echo_bar":echo_bar,"testStatic"
...:testStativ})
>>>fooclid=Foochild()
>>>fooclid.test.Static
<function __main__.testStatic>
>>>fooclid.testStatic()
static method...
>>>fooclid.echo_bar()
True
添加類方法
>>>@classmethod
.... def testClass(cls):
print(cls.bar)
>>>Foochild=type('Foochild',(Foo,),{echo_bar":echo_bar,"testStatic"
...:testStativ,"testClass":testClass})
>>>fooclid=Foochild()
>>>fooclid.testClass()
True
可以看到,在python中,類也是對象,可以動(dòng)態(tài)的創(chuàng)建類。使用關(guān)鍵字 class時(shí)python在幕后做的事情,就是通過元類來實(shí)現(xiàn)的