Prototype-based programming in Python

homeblogmastodonblueskythingiverse



In prototype-based programming there is inheritance but no instantiation. I find myself using a prototype-based style in web applications sometimes. For example I might define a "Field" object that contains the logic for displaying and editing a field in a row of a database table. I might then specialize it in derived objects to perform various kinds of validation.

In Python this can be achieved by neutering a class:

import types

class Prototype:
    class __metaclass__(type):
        def __new__(self, name, bases, dict):
            for member, value in dict.items():
                if type(value) == types.FunctionType:
                    dict[member] = classmethod(value)
            return type.__new__(self, name, bases, dict)

    __new__ = NotImplemented

All methods are converted into classmethods, and the class can not be instantiated. Use of classmethod rather than staticmethod is crucial: When classmethod is used, the method is passed the class as the first argument (much like an instance is passed "self"). This means a method defined in a superclass can call other methods which have possibly been customized in sub-classes.

One trick here: When invoking a super-class's overridden method from a sub-class, one must call Superclass.function.im_func(self, other arguments).




[æ]