我编写了以下代码来帮助强制定义类的某些方法:
def createClassTemplate(name, requiredMethods=[], inherits=object):
def require(name):
def errorRaiser(self, *args, **kwargs):
raise RequireException("method '{}' must be defined.".format(name))
setattr(wrapper, "__name__", name)
return errorRaiser
class Custom(inherits): pass
setattr(Custom, "__name__", name)
for methodName in requiredMethods:
setattr(Custom, methodName, require(methodName))
return Custom
它是这样实现的:
Model = createClassTemplate("Model", ["foo", "bar", "baz"])
class MyClass(Model):
pass
这样,当我缺少一个方法时,调用类将生成一个有意义的错误,表明我未能定义所需的方法。
问题是,上面的代码看起来很笨拙而且不符合 Python 规范。我这样做正确吗?我是否应该强制使用这样的类模板?有没有更好的方法来完成同样的事情?
请您参考如下方法:
您可以使用 ABCMeta元类:
from abc import ABCMeta, abstractmethod
class MyClass:
__metaclass__ = ABCMeta
@abstractmethod
def foo(self):
pass
MyClass 的子类必须覆盖 foo 才能被实例化。
