Class and Object Examples


Class and Object Examples

This document introduces class definition, inheritance, super and object operations.

Module Introduction

Supports class, inheritance, super(), __getitem__, etc. Built-in example:

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

Example Code

Class Definition (class_script.py)

#!pika
class Obj1:
    def test(self):
        print("Obj1.test")

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

t = Test()
#!pika

Type and Instance (type.py excerpt)

#!pika
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')
#!pika

isinstance (isinstance.py excerpt)

#!pika
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')
#!pika

Notes

  • Multiple inheritance and super() behavior follow OpBtPython documentation.