使用type动态创建类

使用type动态创建类

动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。

下面看一个例子:

# 定义一个Person类
class Person(object):

    def __init__(self):
        pass

    def say(self):
        print('say hello')


p = Person()
p.say()               # 输出 say hello

print(type(p))          # 输出 <class '__main__.Person'>

print(type(Person))     # 输出    <class 'type'>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

我们发现,type(Person)输出的是<class 'type'>是type类型。

type()函数可以查看一个类型或变量的类型,Person是一个class(类),它的类型是type,而p是一个 Person的实例,它的类型是Person类。

我们说class(类)的定义是运行时动态创建的,而创建class(类)的方法就是使用type()函数。

eg:

# 定义一个方法
def func(self, word='hello'):
    print('say %s' % word)


Person = type('Person', (object,), dict(say=func))      # 通过type创建Person类

p = Person()

p.say()                 # 输出 say hello

print(type(p))          # 输出 <class '__main__.Person'>

print(type(Person))     # 输出 <class 'type'>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

type函数动态创建类,需要传入3个参数,分别是:

    第一个参数:class的名称
    第二个参数:继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法(tuple单元素写法(obj,));
    第三个参数:class的方法名称与函数绑定,这里我们把函数func绑定到方法名say上。

通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
---------------------
作者:张行之
来源:CSDN
原文:https://blog.csdn.net/qq_33689414/article/details/78295672
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-20 09:29  天涯海角路  阅读(181)  评论(0)    收藏  举报