在子类中强制类变量
我正在为App Engine扩展Python webapp2网络框架,以引入一些缺少的功能(以使创建应用程序更快,更轻松)。
这里的要求之一是每个子类都 需要 具有一些特定的静态类变量。如果实现它们的最佳方法是在我去使用它们时丢失它们,或者有更好的方法,简单地抛出一个异常?
示例(非真实代码):
子类:
class Bar(Foo):
page_name = 'New Page'
必须存在page_name才能在此处进行处理:
page_names = process_pages(list_of_pages)
def process_pages(list_of_pages)
page_names = []
for page in list_of_pages:
page_names.append(page.page_name)
return page_names
-
抽象基类允许声明一个属性抽象,这将强制所有实现类都具有该属性。我仅出于完整性的目的提供此示例,许多pythonista人士认为您提出的解决方案更具pythonic的功能。
import abc class 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() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-bbaeae6b17a6> in <module>() ----> 1 Implementation2() TypeError: Can't instantiate abstract class Implementation2 with abstract methods value