正如lunaryon所说,这是不可能的。包含抽象方法的ABC的真正目的是,它们不能像声明的那样实例化。
但是,可以创建一个对ABC进行内省的实用函数,并动态创建一个虚拟的非抽象类。可以在测试方法/函数内部直接调用此函数,而不必为了测试几种方法而在测试文件中写入样板代码。
def concreter(abclass): """ >>> import abc >>> class Abstract(metaclass=abc.ABCmeta): ... @abc.abstractmethod ... def bar(self): ... return None >>> c = concreter(Abstract) >>> c.__name__ 'dummy_concrete_Abstract' >>> c().bar() # doctest: +ELLIPSIS (<abc_utils.Abstract object at 0x...>, (), {}) """ if not "__abstractmethods__" in abclass.__dict__: return abclass new_dict = abclass.__dict__.copy() for abstractmethod in abclass.__abstractmethods__: #replace each abc method or property with an identity function: new_dict[abstractmethod] = lambda x, *args, **kw: (x, args, kw) #creates a new class, with the overriden ABCs: return type("dummy_concrete_%s" % abclass.__name__, (abclass,), new_dict)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)