网络编程
位置:首页>> 网络编程>> Python编程>> 浅谈Python type的使用

浅谈Python type的使用

作者:a540366413  发布时间:2021-05-17 05:58:59 

标签:Python,type

判断类型

在Python中我们可以使用type进行类型的判断


#我们想看一个对象的的类型可以这样
class A:
 pass
a = A()

type(a) == A #True
#type(obj) 会返回创建a的类型

创建对象


#这个简单,因为type会返回对象的类型,我们可以通过返回的类型创建对象
type(a)()#如果构造函数有参数则应传递相应参数

#上述语句可以分解为

A = type(a)
A()

创建类

看到创建类这个词的时候不知道type使用的朋友会问type怎么能创建类?下面我们介绍使用type创建类


#type(classname,(parents,...),{attribute})
#第一个参数classname是类名,第二个是一个父类元组,没有可填空元组,第三个参数是类属性字典。

O = type("O",(),{'a':1}) #<class 'O'>

a = O()
a.a #1
'''
上述代码可以翻译为
class O:
a=1

a = O()
a.a
'''

来源:https://blog.csdn.net/a540366413/article/details/75221527

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com