【发布时间】:2012-01-12 13:27:43
【问题描述】:
我想打印“复杂”,但什么也没发生,为什么?如何做到这一点?
>>> c = (5+3j)
>>> type(c)
<type 'complex'>
>>> if type(c) == 'complex': print 'complex'
...
>>>
【问题讨论】:
标签: python
我想打印“复杂”,但什么也没发生,为什么?如何做到这一点?
>>> c = (5+3j)
>>> type(c)
<type 'complex'>
>>> if type(c) == 'complex': print 'complex'
...
>>>
【问题讨论】:
标签: python
你可以使用isinstance:
if isinstance(c, complex):
来自文档:
如果 object 参数是 classinfo 参数或其(直接、间接或虚拟)子类的实例,则返回 true。如果 classinfo 是类型对象(新型类)并且 object 是该类型或其(直接、间接或虚拟)子类的对象,则也返回 true。
【讨论】:
isinstance() considered harmful。
>>> c = 5+3j
>>> c
(5+3j)
>>> type(c)
<type 'complex'>
>>> complex
<type 'complex'>
>>> type(c) == complex
True
>>> isinstance(c, complex)
True
>>>
type(c) == complex 的意思是“这绝对是complex 的一个实例,而不是某个子类”。 isinstance(c, complex) 将包含子类。
【讨论】:
试试if isinstance(c,complex): print 'complex'
【讨论】: