gpt4 book ai didi

python - 子类化时出现奇怪的问题?

转载 作者:行者123 更新时间:2023-12-01 05:27:17 26 4
gpt4 key购买 nike

让我们有一个代表 Django Controller 的类,其中一个方法名为 _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_inforequest 参数等于 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'

最佳答案

我不了解这里涉及的 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,情况就不是这样了。

关于python - 子类化时出现奇怪的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21070374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com