type()、isinstance()都是对象类型操作函数,用于判定 Python 对象类型,用哪个函数更好哩?
Python 官网:https://www.python.org/
Free:大咖免费“圣经”教程《 python 完全自学教程》,不仅仅是基础那么简单……
地址:https://lqpybook.readthedocs.io/
自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
—— 华罗庚
本文质量分:
CSDN质量分查询入口:http://www.csdn.net/qc
对于认识 Python 内置对象,Python 为我们准备了多快好省的内置函数 help() 。把想要查看的对象当其参数放入圆括号就行,函数对象作参数对象时不写圆括号。例如——
help(type)
help(isinstance)
其次就是 Python 官方文档,更权威详尽。但对于英文不太好的我来说,虽然祭出词霸大杀器,大多依旧不能很好理解。我学习 Python 的一般路数就是在基本会用时,再探索其官方文档,以资用得正统。
help(type)
Help on class type in module builtins:
class type(object)
type(object) -> the object’s type
type(name, bases, dict, **kwds) -> a new type
…
Data and other attributes defined here:
base =
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
…
class type(object)
class type(name, bases, dict, **kwds)
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.class.
The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute. The bases tuple contains the base classes and becomes the bases attribute; if empty, object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the dict attribute. The following two statements create identical type objects:
>>>
>>> class X:
... a = 1
...
>>> X = type('X', (), dict(a=1))
See also Type Objects.
Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually init_subclass()) in the same way that keywords in a class definition (besides metaclass) would.
See also Customizing class creation.
Changed in version 3.6: Subclasses of type which don’t override type.new may no longer use the one-argument form to get the type of an object.
type(object) -> the object's type
type(name, bases, dict, **kwds) -> a new type
help(isinstance)
Help on built-in function isinstance in module builtins:
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as inisinstance(x, (A, B, ...))
, may be given as the target to check against. This is equivalent toisinstance(x, A) or isinstance(x, B) or ...
etc.
isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised. TypeError may not be raised for an invalid type if an earlier check succeeds.
Changed in version 3.10: classinfo can be a Union Type.
isinstance() 最新官方文档地址:https://docs.python.org/3.12/library/functions.html#isinstance
语法
isinstance(obj, class_or_tuple, /)
isinstance(object, classinfo)
译文,总是有译者理解和观点的影子。对一段语言的多个译文,就是一棵树上的叶子,不会有相同的两片。为不让别人的“经验”对大家造成影响,我在这里直接贴出最新的官方文档。帮助文档也是直接 cv 的 help()输出。
如果您跟我一样,英文“大字不识一箩筐”,也不用着急。下面有例子代码、运行效果截屏,您跟我一样,可以慢慢理解,渐渐会用的。type()、isinstance() 难不住您!
data = 6, 4.5, 'ok', [4, 'ok'], {4: 'ok'}, (4, 'ok'), {4, 'ok'}
print(f"{clear}\n用 type() 查看下面这些对象的类型:\n{', '.join(map(str, data))}\n") # 对 data 字符串格式化,并插值字符串格式化输出结果。
for i in data:
print(f"{i} = {type(i)}")
用示例数据对象,生成类型列表,配伍类型字符串打造类型字符字典。随机打乱类型列表与示例数据比对类型,据所得 bool 值输出 True or False。
print(f"{clear}\n用 type() 判定 Python 基本类型对象的类型:\n{', '.join(map(str, data))}\n")
types = [type(i) for i in data]
type_dict = {mytype: name for mytype,name in zip(types, ['Int', 'Float', 'Str', 'List', 'Dict', 'Tuple', 'Set'])}
shuffle(types) # 随机打乱 Python 基本类型字符串列表。
for k,i in zip(types, data):
print(f"{str(i):>21} is {type_dict[k]}: {type(i) == k}")
print('~'*50)
print(f"{clear}\n用 isinstance() 判定 Python 基本类型对象的类型:\n{', '.join(map(str, data))}\n")
shuffle(types) # 随机打乱类型函数列表。
for k,i in zip(types, data):
print(f"{str(i):>21} is {type_dict[k]}: {isinstance(i, k)}")
print('~'*50)
如您所见,用 isinstance() 判定 Python 对象类型,更优雅,代码更有“意义”,更易读。
myclass = type('DreamElf', (str,), {'name': '梦幻精灵_cq', 'live': '重庆'})
m = myclass()
print(f"{clear}\n type() 生成的新 class:\n{'':~^50}\n\n类型:{type(m)}\n name 属性:{m.name}\n live 属性:{m.live}\n\n{'':~^50}\n")
用 type () 生成 Python 简单的 class 对象,方便快捷,感觉超爽。
print(f"{clear}\n type() 判定自定义 class:\n{'':~^50}\n\n自定义类实例 m 是 myclass 类:{type(m) == myclass }\n自定义类实例 m 是 myclass 类的父类 str :{type(m) == str }\n\n{'':~^50}\n")
print(f"{clear}\n isinstance() 判定自定义 class:\n{'':~^50}\n\n自定义类实例 m 是 myclass 类:{isinstance(m, myclass)}\n自定义类实例 m 是 myclass 类的父类 str :{isinstance(m, str)}\n\n{'':~^50}\n")
print(f"{clear}\n用类型元组作 isinstance() 第二个参数:\n{'':~^50}\n\n")
type_dict[myclass] = 'DreamElf'
types += [myclass]
shuffle(types) # 随机打乱类型列表。
one = ' '
for i in data + [m]:
type3 = sample(types, k=3) # 随机从类型列表中取三个类型。
type3_str = (type_dict[i] for i in type3) # 生成器解析类型名字符串。
print(f"{'':>4} {i} 的类型是 “{', '.join(type3_str)}”:\n{f'{one+str(isinstance(i, tuple(type3)))+one:~^42}':^50}\n")
print(f"\n{'':~^50}\n")
最后一行的是自定义类实例 m ,由于实例化时没有传入字符参数,Python 默认是空白字符串 ‘’,所以是空白。
如果实例化时传入参数——
myclass = type('DreamElf', (str,), {'name': '梦幻精灵_cq', 'live': '重庆'})
m = myclass('梦幻精灵_cq')
myclass = type('DreamElf', (str,), {'name': '梦幻精灵_cq', 'live': '重庆'})
m = myclass(666)
参考资料:
CSDN 博文——
(源码较长,点此跳过源码)
#!/sur/bin/nve python
# coding: utf-8
from random import shuffle
from random import sample
clear = '\033[2J' # Linux 下的清屏字符串。
data = [6, 4.5, 'ok', [4, 'ok'], {4: 'ok'}, (4, 'ok'), {4, 'ok'}]
print(f"{clear}\n用 type() 查看下面这些对象的类型:\n{', '.join(map(str, data))}\n") # 对 data 字符串格式化,并插值字符串格式化输出结果。
for i in data:
print(f"{i} = {type(i)}")
# 判定对象类型
print(f"{clear}\n用 type() 判定 Python 基本类型对象的类型:\n{', '.join(map(str, data))}\n")
types = [int, float, str, list, tuple, set, dict]
type_dict = {mytype: name for mytype,name in zip(types, ['Int', 'Float', 'Str', 'List', 'Dict', 'Tuple', 'Set'])}
shuffle(types) # 随机打乱 Python 基本类型字符串列表。
for k,i in zip(types, data):
print(f"{str(i):>21} is {type_dict[k]}: {type(i) == k}")
print('~'*50)
print(f"{clear}\n用 isinstance() 判定 Python 基本类型对象的类型:\n{', '.join(map(str, data))}\n")
shuffle(types) # 随机打乱类型函数列表。
for k,i in zip(types, data):
print(f"{str(i):>21} is {type_dict[k]}: {isinstance(i, k)}")
print('~'*50)
# type() 创建简单类
myclass = type('DreamElf', (str,), {'name': '梦幻精灵_cq', 'live': '重庆'})
m = myclass(666)
print(f"{clear}\n type() 生成的新 class:\n{'':~^50}\n\n类型:{type(m)}\n name 属性:{m.name}\n live 属性:{m.live}\n\n{'':~^50}\n")
# 判定自定义类
print(f"{clear}\n type() 判定自定义 class:\n{'':~^50}\n\n自定义类实例 m 是 myclass 类:{type(m) == myclass }\n自定义类实例 m 是 myclass 类的父类 str :{type(m) == str }\n\n{'':~^50}\n")
print(f"{clear}\n isinstance() 判定自定义 class:\n{'':~^50}\n\n自定义类实例 m 是 myclass 类:{isinstance(m, myclass)}\n自定义类实例 m 是 myclass 类的父类 str :{isinstance(m, str)}\n\n{'':~^50}\n")
# 用类型元组作 isinstance() 第二个参数。
print(f"{clear}\n用类型元组作 isinstance() 第二个参数:\n{'':~^50}\n\n")
type_dict[myclass] = 'DreamElf'
types += [myclass]
shuffle(types) # 随机打乱类型列表。
one = ' '
for i in data + [m]:
type3 = sample(types, k=3) # 随机从类型列表中取三个类型。
type3_str = (type_dict[i] for i in type3) # 生成器解析类型名字符串。
print(f"{'':>4} {i} 的类型是 “{', '.join(type3_str)}”:\n{f'{one+str(isinstance(i, tuple(type3)))+one:~^42}':^50}\n")
print(f"\n{'':~^50}\n")
我的HOT博:
本次共计收集 210 篇博文笔记信息,总阅读量 33.91w,平均阅读量 1614。已生成 22 篇阅读量不小于 3000 的博文笔记索引链接。数据采集于 2023-05-22 05:29:13 完成,用时 4 分 49.29 秒。
精品文章:
来源:老齐教室
◆ Python 入门指南【Python 3.6.3】
好文力荐:
CSDN实用技巧博文: