python - 使用 isinstance() 可以覆盖类型

标签 python python-3.x overwrite isinstance

使用isinstance()更改了 dict 的类类型 为什么会发生这种情况?我知道使用内置函数会阻止这种情况,但我想更好地理解为什么会发生这种情况。

250     def printPretty(records,num,title='Summary:'):
251         import pdb; pdb.set_trace()
252         if isinstance(records, list):
253             print ("\n{}\n{}".format(title.center(120),"="*120))
254             table = list()
255             for i in records:
...
263         elif isinstance(records, dict):
264  ->         for key in records:
265                 if isinstance(records[key], Param):
266                     for i in records[key]:
267                         print (i)
268                 print ("")
269     
(Pdb) type(records)
<class 'dict'>
(Pdb) type(dict)
<class 'type'><b>

最佳答案

我认为您的困惑在于 type(dict) != dict。让我们完全放弃您的示例,除了最后两行,我将使用交互式 python 来呈现。

>>> type(dict)
<type 'type'>
>>> type(dict())
<type 'dict'>

这是因为dict不是字典,而是字典的类型。 dict(){}(或 {1:2, ...})是字典的实例。这些实例的类型为 dict,并满足 isinstance(___, dict)

关于python - 使用 isinstance() 可以覆盖类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44080357/

相关文章:

python - 对 Pandas 中的每隔一行进行子集化?

python - 如何关闭弹出通知?使用 selenium python 进行自动化测试

python - 为什么我的自定义异常 unpickle 失败

python-3.x - 比较 Python 中彩票程序的两位数字

混帐 merge : overwrite untracked files

python - 如何使用 Python 填写使用下拉日历选择日期的 Web 表单?

python - 将队列转储到python中的列表/数组中

python-3.x - python 3.5 : "TypeError: memoryview: a bytes-like object is required, not ' str'"

css - Bootstrap 字体覆盖标题和正文的不同字体

c - 如何在c中重写char数组?