成都网站建设设计

将想法与焦点和您一起共享

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

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.

本文标题:pythonClass:面向对象高级编程元类:type
分享路径:http://chengdu.cdxwcx.cn/article/jidses.html