类和对象示例

January 30, 2026

类和对象示例

本文档介绍类定义、继承、super 和对象操作。示例来源:doc/pikapython.com/examples/builtins/

模块简介

支持 class、继承、super()__getitem__ 等。内嵌示例:

class C:
    def f(self):
        return 1
o = C()
print(o.f())

示例代码

类定义(class_script.py)

class Obj1:
    def test(self):
        print("Obj1.test")

class Test:
    a = Obj1()
    a.test()

t = Test()

类型与实例(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()
assert ttt1.test() == 'test 1'
assert type(ttt1) == Test1
print('PASS')

isinstance(isinstance.py 节选)

assert isinstance(10, int) == True
assert isinstance("Hello", str) == True
class BaseClass(object):
    def __init__(self):
        self.a = 1
class DerivedClass(BaseClass):
    def __init__(self):
        super().__init__()
        self.b = 2
derived_instance = DerivedClass()
assert isinstance(derived_instance, BaseClass) == True
print('PASS')

注意事项

  • 多继承与 super() 行为以 PikaPython 文档为准。

相关链接