子类化的奇怪问题?

时间:2014-01-12 01:56:28

标签: python django python-2.7 inheritance

让我们有一个代表Django控制器的类,其中一个方法叫做_onSuccess

class ConfirmController(object):
    ...
    def _onSuccess(self, controller):
      ...

该类稍后将实例化为:

def credit_confirm_info(request, payment_module, template='/some/template.html'):
    controller = ConfirmController(request, payment_module)
    controller.confirm()   # this method calls self._onSuccess
    return controller.response
credit_confirm_info = never_cache(credit_confirm_info)

我正在尝试使用ConfirmController的子类:

class ConfirmControllerEx(ConfirmController):
    def _onSuccess(self, controller):
        # shortened to demonstrate even simple call to super
        # causes a different behaviour
        super(ConfirmControllerEx, self)._onSuccess(controller)

我可能在python学习中遗漏了一些东西但是有人可以解释为什么以上的_onSuccess等同于原始方法? 如果我使用上面的子类ConfirmControllerEx

def credit_confirm_info(request, payment_module, template='/some/template.html'):
    controller = ConfirmControllerEx(request, payment_module)
    controller.confirm()   # this method calls self._onSuccess
    return controller.response
credit_confirm_info = never_cache(credit_confirm_info)

我收到NoneType has no method has_header错误,例如再次调用credit_confirm_info,但request参数等于None

我希望对_onSuccess进行简单调用的子类和子类方法super与原始方法不同。我在这里错过了什么吗?

更新(异常追溯):

    Traceback:
File "/home/dunric/Projects/Example.com/satchmo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/dunric/Projects/Example.com/satchmo/gastroceny_cz/localsite/views.py" in cod_confirm_info
  279.             template='shop/checkout/cod/confirm.html')
File "/home/dunric/Projects/Example.com/satchmo/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  90.         add_never_cache_headers(response)
File "/home/dunric/Projects/Example.com/satchmo/lib/python2.7/site-packages/django/utils/cache.py" in add_never_cache_headers
  129.     patch_response_headers(response, cache_timeout=-1)
File "/home/dunric/Projects/Example.com/satchmo/lib/python2.7/site-packages/django/utils/cache.py" in patch_response_headers
  119.     if not response.has_header('Last-Modified'):

    Exception Type: AttributeError at /checkout/cod/confirm/
    Exception Value: 'NoneType' object has no attribute 'has_header'

1 个答案:

答案 0 :(得分:2)

我不知道这里涉及的django的具体细节,但是这个方法:

def _onSuccess(self, controller):
    # shortened to demonstrate even simple call to super
    # causes a different behaviour
    super(ConfirmControllerEx, self)._onSuccess(controller)

等同于父类的_onSuccess。它通过super 调用父实现,但忽略了该调用返回的任何内容,只返回None(隐式地,通过执行到达方法定义的末尾)。鉴于你后来得到的错误似乎表明你有一个None对象(NoneType的实例),其中还有其他东西,这就是我对错误的猜测。但是,如果_onSuccess方法的合同始终返回None,那就不会这样了。