gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:23 26 4
gpt4 key购买 nike

我用 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))

关于python - Python 中具有特定参数的抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com