Prototype-based programming in Python

home | blog

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).

当前网页内容, 由 大妈 ZoomQuiet 使用工具: ScrapBook :: Firefox Extension 人工从互联网中收集并分享;
若有不妥, 欢迎评注提醒:


点击注册~> 获得 100$ 体验券: DigitalOcean Referral Badge

订阅 substack 体验古早写作:

关注公众号, 持续获得相关各种嗯哼:


关于 ~ DebugUself with DAMA ;-)
公安备案号: 44049002000656 ...::