【问题标题】:Use of isinstance() can overwrite type [duplicate]使用 isinstance() 可以覆盖类型
【发布时间】:2017-10-20 04:37:09
【问题描述】:

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>

【问题讨论】:

  • isinstance 不会改变事物的类型。此处没有任何内容表明任何内容的类型已更改。
  • 您认为为什么会发生任何类型更改?
  • 您的问题表明您期望与您最后拨打的type 电话有一些不同的结果,但不清楚您的期望是什么。你能澄清一下你的预期和原因吗?

标签: python python-3.x overwrite isinstance


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!完全正确,我很困惑,你的答案澄清了。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多