Skip to main content
 首页 » 编程设计

python之Python 中具有特定参数的抽象方法

2024年11月01日7shihaiming

我用 abc 包实现了抽象类。下面的程序没有问题。

有什么方法可以让它失败,因为抽象 MyMethod 确实有一个参数 a 但是类 Derivative 中 'MyMethod' 的实现没有?所以我不仅要指定接口(interface)类 Base 中的方法,还要指定这些方法的参数。

import abc 
 
#Abstract class 
class Base(object): 
    __metaclass__  = abc.ABCMeta 
 
    @abc.abstractmethod 
    def MyMethod(self, a): 
        'MyMethod prints a' 
 
 
class Derivative(Base) 
 
    def MyMethod(self): 
        print 'MyMethod' 

请您参考如下方法:

下面的代码是从代理类复制而来的,其工作方式类似。它检查是否存在所有方法以及方法签名是否相同。该工作在 _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))