下面的代码是从代理类复制的,其工作方式类似。它检查所有方法是否存在以及方法签名是否相同。这项工作在 _checkImplementation() 中完成。注意以 ourf 和 theirf 开头的两行;_getMethodDeclaration() 将签名转换为字符串。在这里,我选择要求两者完全相同:
@classmethod
def _isDelegatableIdentifier(cls, methodName):
return not (methodName.startswith('_') or methodName.startswith('proxy'))
@classmethod
def _getMethods(cls, aClass):
names = sorted(dir(aClass), key=str.lower)
attrs = [(n, getattr(aClass, n)) for n in names if cls._isDelegatableIdentifier(n)]
return dict((n, a) for n, a in attrs if inspect.ismethod(a))
@classmethod
def _getMethodDeclaration(cls, aMethod):
try:
name = aMethod.__name__
spec = inspect.getargspec(aMethod)
args = inspect.formatargspec(spec.args, spec.varargs, spec.keywords, spec.defaults)
return '%s%s' % (name, args)
except TypeError, e:
return '%s(cls, ...)' % (name)
@classmethod
def _checkImplementation(cls, aImplementation):
"""
the implementation must implement at least all methods of this proxy,
unless the methods is private ('_xxxx()') or it is marked as a proxy-method
('proxyXxxxxx()'); also check signature (must be identical).
@param aImplementation: implementing object
"""
missing = {}
ours = cls._getMethods(cls)
theirs = cls._getMethods(aImplementation)
for name, method in ours.iteritems():
if not (theirs.has_key(name)):
missing[name + "()"] = "not implemented"
continue
ourf = cls._getMethodDeclaration(method)
theirf = cls._getMethodDeclaration(theirs[name])
if not (ourf == theirf):
missing[name + "()"] = "method signature differs"
if not (len(missing) == 0):
raise Exception('incompatible Implementation-implementation %s: %s' % (aImplementation.__class__.__name__, missing))