0
点赞
收藏
分享

微信扫一扫

python学习高级篇(part5)--内置函数type

学习笔记,仅供参考,有错必纠


内置函数type



内置函数​​type()​​用于获得指定对象的类型,比如:实例对象类型是其对应的类对象



  • 举个例子

代码:

class MyClass(object):
pass

mc = MyClass()

print(type(mc))
print(type(18))
print(type('abc'))

输出:

<class '__main__.MyClass'>
<class 'int'>
<class 'str'>



  • 举个例子2

代码:

print(type(MyClass))
print(type(int))
print(type(str))

输出:

<class 'type'>
<class 'type'>
<class 'type'>

类对象的类型是​​type​​,也就是说,类对象是​​type​​的一个实例对象



  • 举个例子3

代码:

def do_sth():
pass

print(type(do_sth))
print(type(print))

输出:

<class 'function'>
<class 'builtin_function_or_method'>

自定义函数对象的类型是​​function​​​;
内置函数对象的类型是​​​builtin_function_or_method​



  • 举个例子4

代码:

print(type(18) == int)
print(type('abc') == str)

import types
print(type(do_sth) == types.FunctionType)
print(type(print) == types.BuiltinFunctionType)

输出:

True
True
True
True

可以使用运算符​​==​​判断某个对象的类型是否是指定的类型。

对于基本数据类型,可以直接使用其对应的类名;

如果不是基本数据类型,需要使用标准库中的模块​​types​​中定义的变量。

举报

相关推荐

0 条评论