动态建立类
1. type()
使用方法:类名=type(类名,继承的父类集合)
使用type()
创建出mood类,无需定义class mood(object):
>>> def now(who): #创建一个方法
print('anxious')
#使用type动态创建一个类
>>> Mood=type('me',(object),dict(now=now)) #注意第二册参数是tuple
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
Mood=type('me',(object),dict(now=now))
TypeError: type() argument 2 must be tuple, not type
>>> Mood=type('me',(object,),dict(now=now))
>>> Mood.now('me') #给函数赋值
anxious
>>> print(type(Mood)) #输出Mood的类型
<class 'type'> #一个类
>>> print(type(now))
<class 'function'>
>>> s=Mood() #创建类的实例
>>> print(type(s)) #输出实例的类型
<class '__main__.me'> #一个类,包括方法:main、me