在 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.