抽象基类允许声明一个属性抽象,这将强制所有实现类都具有该属性。我仅出于完整性的目的提供此示例,许多pythonista人士认为您提出的解决方案更具pythonic的功能。
import abcclass base(object): __metaclass__ = abc.ABCmeta @abc.abstractproperty def value(self): return 'Should never get here'class Implementation1(base): @property def value(self): return 'concrete property'class Implementation2(base): pass # doesn't have the required property
试图实例化第一个实现类:
print Implementation1()Out[6]: <__main__.Implementation1 at 0x105c41d90>
试图实例化第二个实现类:
print Implementation2()---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)<ipython-input-4-bbaeae6b17a6> in <module>()----> 1 Implementation2()TypeError: Can't instantiate abstract class Implementation2 with abstract methods value
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)