使用decorator检查子类是否实现了父类要求必须实现的方法,decorator,这里的decorator
使用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
相关内容
- python使用rstrip()函数移除行末空白字符,pythonrstrip,pyt
- python从网页中解析网页的字符编码,python字符,[Python]代
- Python使用win32api获取DLL和EXE文件版本号,,[Python]代码i
- python获得随机字符串,python字符串,如下代码生成随机密
- python读写windows注册表,python读写windows,本文封装了_wi
- python使用pickle,json等序列化dict,picklejson,PersistentDi
- Python删除指定目录下的过期文件,,import osimp
- python使用atexit在程序退出时清理资源,pythonatexit,当进程
- python读取windows系统信息,python读取系统信息,需要使用
- python在windows下创建隐藏窗口的子进程,python窗口,impo
评论关闭