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 人工从互联网中收集并分享;
内容版权归原作者所有;
本人对内容的有效性/合法性不承担任何强制性责任.
若有不妥, 欢迎评注提醒:

或是邮件反馈可也:
askdama[AT]googlegroups.com


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

订阅 substack 体验古早写作:


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


自怼圈/年度番新

DU22.4
关于 ~ DebugUself with DAMA ;-)
粤ICP备18025058号-1
公安备案号: 44049002000656 ...::