打算是用:
xxx is str
xxx is dict
去判断的:
<code> def showVideoCallback(self, response): print("showVideoCallback: response.url=%s" % (response.url)) curShowInfoDictOrActId = response.save print("curShowInfoDictOrActId=%s" % curShowInfoDictOrActId) act_id = "" curShowInfoDict = None if curShowInfoDictOrActId is str: act_id = curShowInfoDictOrActId print("para is curActId") elif curShowInfoDictOrActId is dict: curShowInfoDict = curShowInfoDictOrActId print("para is curShowInfoDict") else: print("!!! can not recognize parameter for showVideoCallback") </code>
结果无法识别。
然后去搜:
python 3 check variable type
Python: Checking Type of Variable – Code Yarns 👨💻
isinstance(s, str)
isinstance(d, dict)
How to check type of object in Python? – Stack Overflow
isinstance(v, type_name)
type(v) is type_name
type(v) == type_name
What is the Pythonic way to check if type of a variable is string? – Quora
How to Use Static Type Checking in Python 3.6 – Adam Geitgey – Medium
How to determine a Python variable’s type? – Stack Overflow
type(i) is int
那isinstance和type有何区别?
python isinstance vs type
python – What are the differences between type() and isinstance()? – Stack Overflow
python – isinstance(foo,bar) vs type(foo) is bar – Stack Overflow
type() vs. isinstance() in Python – Stereochrome
Python中为什么推荐使用isinstance来进行类型判断?而不是type – 简书
【总结】
isinstance:判断某个变量是否是某个类型(或类)的示例
type:只是类型判断,如果是父类集成,则不相等
举例:
<code>class Vehicle: pass class Truck(Vehicle): pass isinstance(Vehicle(), Vehicle) # returns True type(Vehicle()) == Vehicle # returns True isinstance(Truck(), Vehicle) # returns True type(Truck()) == Vehicle # returns False, and this probably won't be what you want. </code>
以及:
有些情况下判断结果是错的,不是希望的结果:
<code>class A(): pass class B(): pass a = A() b = B() print(type(a) is type(b)) # True </code>
暂时就不去研究更加深入的区别了。
结论:
当想要判断变量类型是,优先使用isinstance
此处自己用的是:
<code> act_id = "" curShowInfoDict = None if isinstance(curShowInfoDictOrActId, str): act_id = curShowInfoDictOrActId print("para is curActId") elif isinstance(curShowInfoDictOrActId, dict): curShowInfoDict = curShowInfoDictOrActId print("para is curShowInfoDict") else: print("!!! can not recognize parameter for showVideoCallback") </code>
另外别人举例说明,isinstance支持多个可选的判断:
<code>>>> isinstance(2, float) False >>> isinstance('a', (str, unicode)) True >>> isinstance((2, 3), (str, list, tuple)) True </code>
转载请注明:在路上 » 【已解决】Python 3中判断变量类型