#傳統編程
class A1:
def __init__(self,name='a1'):
self.name = name
print('a1 init')
def show(self):
print('a1 show')
#元編程(用代碼生成代碼)
def __init__(self,name='b1'):
self.name = name
print('b1 init')
def show(self):
print('b1 show')
B1 = type('B1',(object,),{'__init__':__init__,'show':show})
#測試
print(A1)
print(type(A1))
print(A1.__dict__)
print(A1.mro())
print(A1().__dict__)
print('===========================')
print(B1)
print(type(B1))
print(B1.__dict__)
print(B1.mro())
print(B1().__dict__)
運行結果:
<class '__main__.A1'>
<class 'type'>
{'__doc__': None, '__init__': <function A1.__init__ at 0x7f9a0b5fcbf8>, 'show': <function A1.show at 0x7f9a0b5fcc80>, '__dict__': <attribute '__dict__' of 'A1' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A1' objects>}
[<class '__main__.A1'>, <class 'object'>]
a1 init
{'name': 'a1'}
===========================
<class '__main__.B1'>
<class 'type'>
{'__doc__': None, '__init__': <function __init__ at 0x7f9a0cbbaf28>, 'show': <function show at 0x7f9a0b5fcd08>, '__dict__': <attribute '__dict__' of 'B1' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'B1' objects>}
[<class '__main__.B1'>, <class 'object'>]
b1 init
{'name': 'b1'}