使用decorator检查子类是否实现了父类要求必须实现的方法,decorator,这里的decorator


这里的decorator修饰了类的__init__函数,检查子类是否实现了父类要求实现的方法。

以下代码使用decorator,要求python版本至少为2.6

def require_methods(*method_args):    """Class decorator to require methods on a subclass.    Example usage    ------------    @require_methods('m1', 'm2')    class C(object):        'This class cannot be instantiated unless the subclass defines m1() and m2().'        def __init__(self):            pass    """    def fn(cls):        orig_init = cls.__init__        def init_wrapper(self, *args, **kwargs):            for method in method_args:                if (not (method in dir(self))) or \                   (not callable(getattr(self, method))):                    raise Exception("Required method %s not implemented" % method)            orig_init(self, *args, **kwargs)        cls.__init__ = init_wrapper        return cls    return fn

评论关闭