Classes

Classes in RPython are very similar with Python. You can inherit a class and override methods.

Attention

There are some restrictions in RPython: 1) methods and other class attributes do not change after startup, 2) only single inheritance is supported.

class Animal(object):
    def __init__(self, name):
        self.name = name

    def greet(self):
        self.say("I'm " + self.name + ".")

    def say(self, msg): pass

class Cat(Animal):
    def say(self, msg):
        print "Meow, " + msg

class Dog(Animal):
    def say(self, msg):
        print "Wuff, " + msg

class Playground(object):
    def __init__(self, size):
        self._item = [None] * size

    def __setitem__(self, index, animal):
        self._item[index] = animal

    def __getitem__(self, index):
        return self._item[index]

def classes():
    c = Cat("Kitty")
    c.greet()           # Meow, I'm Kitty.

    d = Dog("Buddy")
    d.greet()           # Wuff, I'm Buddy.

    p = Playground(3)   # create a playground with size of 3
    p[0] = c
    p[1] = d

    p[0].greet()        # Meow, I'm Kitty.
    p[1].greet()        # Wuff, I'm Buddy.

def entry_point(argv):
    classes()
    return 0

def target(*args): return entry_point
if __name__ == "__main__": import sys; entry_point(sys.argv)

Multiple inheritance only supported with mixin.

Attention

use rpython.rlib.objectmodel.import_from_mixin(M) in a class body to copy the whole content of a class M. This can be used to implement mixins: functions and staticmethods are duplicated (the other class attributes are just copied unmodified).

from rpython.rlib.objectmodel import import_from_mixin

class ActivityMixin(object):
    def eat(self, food):
        print "Eating " + food

class Animal(object):
    import_from_mixin(ActivityMixin)    # import ActivityMixin

    def __init__(self, name):
        self.name = name

    def greet(self):
        self.say("I'm " + self.name + ".")

    def say(self, msg): pass

class Cat(Animal):
    def say(self, msg):
        print "Meow, " + msg

# class Cat2(Animal, ActivityMixin):    # multiple inheritance only supported with mixin
#     pass

class Dog(Animal):
    def say(self, msg):
        print "Wuff, " + msg

def classes():
    c = Cat("Kitty")
    c.greet()           # Meow, I'm Kitty.
    c.eat("cat food")

def entry_point(argv):
    classes()
    return 0

def target(*args): return entry_point
if __name__ == "__main__": import sys; entry_point(sys.argv)