Python使用type动态创建类操作示例
作者:张行之 时间:2021-05-20 11:47:02
本文实例讲述了Python使用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'>
运行结果:
say hello
<class '__main__.Person'>
<class 'type'>
我们发现,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'>
运行结果:
say hello
<class '__main__.Person'>
<class 'type'>
type函数动态创建类,需要传入3个参数,分别是:
第一个参数:class的名称
第二个参数:继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法(tuple单元素写法
(obj,)
);第三个参数:class的方法名称与函数绑定,这里我们把函数func绑定到方法名say上。
通过type()
函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/qq_33689414/article/details/78295672
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3的url编码和解码,自定义gbk、utf-8的例子
Python数据结构与算法之完全树与最小堆实例
python使用response.read()接收json数据的实例
pytorch中tensor的合并与截取方法
![](https://img.aspxhome.com/file/2023/9/111939_0s.jpg)
Python轻松破解加密压缩包教程详解
![](https://img.aspxhome.com/file/2023/3/71393_0s.png)
瞬间的设计(四)【碳酸饮料会】
![](https://img.aspxhome.com/file/UploadPic/20101/11/70618be7941ddd0f1be611656977bc15-93s.jpg)
[翻译]网页设计中的模式窗口
![](https://img.aspxhome.com/file/UploadPic/20095/29/376600_124350365243zv-44s.jpg)
Python图像特效之模糊玻璃效果
![](https://img.aspxhome.com/file/2023/1/117401_0s.jpg)
asp日期时间格式化函数
IE7的web标准之道 Ⅰ
![](https://img.aspxhome.com/file/UploadPic/20088/13/200881312500620s.gif)
PHP For循环字母A-Z当超过26个字母时输出AA,AB,AC
Python实现按当前日期(年、月、日)创建多级目录的方法
![](https://img.aspxhome.com/file/2023/7/95667_0s.png)
六个Python3中使用最广泛的内置函数总结
sql基本查询语句介绍
怎么样才能设计出漂亮的网页?
Python简明讲解filter函数的用法
Python 如何实现变量交换
Python提取支付宝和微信支付二维码的示例代码
![](https://img.aspxhome.com/file/2023/2/70242_0s.jpg)
ASP编程如何执行存储过程?
python自动化测试三部曲之request+django实现接口测试
![](https://img.aspxhome.com/file/2023/3/114513_0s.png)