類的兩種方法

普通方式

1 class foo(object):
2     def __init__(self, name):
3         self.name = name
4 
5 
6 f = foo('gdr')
7 
8 print(type(f))
9 print(type(foo))

特殊方式

 1 此列子告訴咱們類是由type類實例化產生的
 2 def nothing(self):
 3     print('你好,飛天豬少女%s' % self.name)
 4 
 5 
 6 def __init__(self, name):
 7     self.name = name
 8 
 9 
10 pig = type('pig', (object,), {'test': nothing,
11                               '__init__': __init__})
12 #type第一個參數:類名
13 #type第二個參數:當前類的基類
14 #type第三個參數:類的成員
15 
16 fly = pig('djj')
17 fly.test()
18 print(type(pig))
1 輸出結果:
2 >>> 你好,飛天豬少女djj
3 >>> <class 'type'>
相關文章
相關標籤/搜索