type的用法:
1、普通的type用法:检查类型class my(object):
def hello(self, name='world'):
print('Hello, %s.' % name)
h = my()
print(type(my))
print(type(h))
运行结果:
my是class, 所以它的类型是type,
h是class的实例,所以它的类型是class my。
2、动态创建Class
格式:
a.定义一个函数,
b.实体类名 = type(类名, (继承, ), dict(类的方法=函数))def fn(self, name='world'): # 先定义函数
print('Hello, %s.' % name)
hl = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
h = hl()
h.hello()
运行结果:Hello, world.