January 30, 2026
类型检查示例
本文档介绍 type() 与 isinstance() 的用法。示例来源:doc/pikapython.com/examples/builtins/。
模块简介
支持 type(obj) 获取类型、isinstance(obj, class) 判断实例关系。内嵌示例:
assert type(1) == int
assert isinstance('a', str)
示例代码
type 函数(type.py)
class Test1:
def test(self):
return 'test 1'
class Test2:
def test(self):
return 'test 2'
t1 = Test1()
tt1 = type(t1)
ttt1 = tt1()
t2 = Test2()
tt2 = type(t2)
ttt2 = tt2()
assert ttt1.test() == 'test 1'
assert ttt2.test() == 'test 2'
assert type(ttt1) == Test1
assert type(ttt2) == Test2
assert type(ttt1) != type(ttt2)
assert type(ttt1) != Test2
assert type(ttt2) != Test1
print('PASS')
说明:type(实例) 得到类对象,该类对象可再次调用以创建新实例;用 == 比较类型是否相同。
isinstance 检查(isinstance.py)
# Testing with builtin types
assert isinstance(10, int) == True
assert isinstance("Hello, world!", str) == True
assert isinstance([1, 2, 3, 4, 5], list) == True
assert isinstance({"key": "value"}, dict) == True
assert isinstance(3.14, float) == True
assert isinstance(object(), object) == True
assert isinstance(10, str) == False
class MyClass:
pass
class BaseClass(object):
def __init__(self):
self.a = 1
class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
self.b = 2
base_instance = BaseClass()
derived_instance = DerivedClass()
# Instances of DerivedClass should also be instances of BaseClass
assert isinstance(MyClass(), object) == True
assert isinstance(base_instance, object) == True
assert isinstance(base_instance, BaseClass) == True
assert isinstance(derived_instance, BaseClass) == True
# However, instances of BaseClass are not instances of DerivedClass
assert isinstance(base_instance, DerivedClass) == False
# And instances of DerivedClass are, of course, instances of DerivedClass
assert isinstance(derived_instance, DerivedClass) == True
print('PASS')
说明:isinstance(obj, Class) 对内置类型和继承关系均有效,子类实例对基类返回 True。
isinstance 在逻辑分支中的使用(issue_isinstance.py)
class scr_Text:
def cus_print(self, data, end='\n'):
str_buf = ""
if isinstance(data, str):
str_buf = str_buf + data
elif isinstance(data, int):
str_buf = str_buf + str(data)
else:
str_buf = "The type is not recognized"
str_buf = str_buf + end
screen = scr_Text()
screen.cus_print(12)
screen.cus_print(12)
screen.cus_print(12)
screen.cus_print(12)
print('PASS')
说明:根据 isinstance 分支处理不同数据类型,实现简单多态或格式化输出。
注意事项
- 用
type(x) == Type只判断精确类型,不包含子类;若需考虑继承,宜用isinstance(x, Type)。 - 在 OPBTPython 中,内置类型与 PikaPython 文档保持一致,行为可能与 CPython 有细微差异。