Advanced Class Usage Examples


Advanced Class Usage Examples

This document introduces class attributes vs instance attributes, inheritance and polymorphism, and inheriting standard library classes.

Module Introduction

Covers class/instance attributes, __init__, subclass method overriding, inheriting PikaStdLib, etc. Built-in example:

#!pika
class C:
    a = 1
    def __init__(self):
        self.a = 2
o = C()
print(o.a)
#!pika

Example Code

Class Parameters and Attributes (classpar1.py)

#!pika
class Test:
    a = 1
    b = 'test'
    def __init__(self):
        self.a = 2
        self.b = 'pewq'

print(Test.a)
print(Test.b)

test = Test()
print(test.a)
print(test.b)
#!pika

Note: Test.a, Test.b are class attributes; self.a, self.b assigned in __init__ are instance attributes, after instantiation access gets instance attributes (2 and ‘pewq’).

Inheritance and Polymorphism (main.py)

#!pika
# need core >= v1.4.0
import PikaStdLib

class people:
    def do_hi(self):
        print('hello i am people')
    def hi(self):
        self.do_hi()

class student(people):
    def do_hi(self):
        print('hello i am student')

class mymem(PikaStdLib.MemChecker):
    def mymax(self):
        print('mem used max: ' + str(self.getMax()) + ' kB')

p = people()
s = student()

p.hi()
s.hi()

mem = mymem()
mem.mymax()
#!pika

Note: people defines do_hi and hi, student inherits and overrides do_hi, under polymorphism s.hi() calls subclass’s do_hi. mymem inherits PikaStdLib.MemChecker and extends mymax(), demonstrates inheriting standard library classes. Requires firmware to provide PikaStdLib with compatible version.

Expected Output

  • Class attributes output: 1, test; instance attributes output: 2, pewq.
  • main.py: First outputs “hello i am people”, then “hello i am student”, finally outputs current max memory usage (in kB).

Notes

  • When instance attributes “shadow” class attributes, accessing via instance gets instance attributes.
  • When inheriting classes from PikaStdLib and other modules, confirm device firmware includes corresponding modules with API compatibility.