python Class:面向对象高级编程 元类:type

type的用法:

1、普通的type用法:检查类型

class my(object):
    def hello(self, name='world'):
        print('Hello, %s.' % name)

h = my()       
print(type(my))        
print(type(h))

运行结果:

<type 'type'>
<class '__main__.my'>

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.


猜你喜欢

转载自blog.51cto.com/13502993/2147832
今日推荐