Python 中检查类型的主要方法是什么?


如果你要检查一个对象 x 是否是确切某一类型的实例(不是子类型),你可以使用 type 来获得它的类型,然后使用 is 语句进行检查。

示例

x = "Hello"
if type(x) is str:
   print("x is an instance of str")

输出

这将产生下面的输出

x is an instance of str

如果你要检查 x 是否是 MyClass 或 MyClass 的任何子类的实例,你可以使用 isinstance 方法调用。

示例

x = "Hello"
if isinstance(x, str):
   print("x is an instance of str")

输出

这将产生下面的输出

x is an instance of str

更新于: 2020 年 3 月 5 日

116 次浏览

启动你的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.