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

时间:2014-03-22 18:49:21

标签: python class oop abstract abc

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

有没有办法让它失败,因为抽象MyMethod确实有一个参数a但是Derivative类中'MyMethod'的实现没有?所以我不仅要指定接口类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'

1 个答案:

答案 0 :(得分:2)

以下代码是从代理类中复制的,类似的代码类。它检查所有方法是否存在以及方法签名是否相同。这项工作是在_checkImplementation()中完成的。注意以ourf和thef开头的两行; _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))