在子类中强制执行类变量 [英] Enforcing Class Variables in a Subclass

查看:52
本文介绍了在子类中强制执行类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 App Engine 扩展 Python webapp2 网络框架,以引入一些缺失的功能(以便更快、更轻松地创建应用).

I'm working on extending the Python webapp2 web framework for App Engine to bring in some missing features (in order to make creating apps a little quicker and easier).

这里的要求之一是每个子类需要有一些特定的静态类变量.实现此目的的最佳方法是在我使用它们时简单地抛出异常,还是有更好的方法?

One of the requirements here is that each subclass needs to have some specific static class variables. Is the best way to achieve this to simply throw an exception if they are missing when I go to utilise them or is there a better way?

示例(不是真正的代码):

Example (not real code):

子类:

class Bar(Foo):
  page_name = 'New Page'

page_name 需要存在才能在此处处理:

page_name needs to be present in order to be processed here:

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

推荐答案

抽象基类允许声明一个属性抽象,这将强制所有实现类拥有该属性.我只是为了完整性提供这个例子,许多 pythonistas 认为你提出的解决方案更 pythonic.

Abstract Base Classes allow to declare a property abstract, which will force all implementing classes to have the property. I am only providing this example for completeness, many pythonistas think your proposed solution is more 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

尝试实例化第一个实现类:

Trying to instantiate the first implementing class:

print Implementation1()
Out[6]: <__main__.Implementation1 at 0x105c41d90>

尝试实例化第二个实现类:

Trying to instantiate the second implementing class:

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

这篇关于在子类中强制执行类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆