Python中的菱形问题:从所有父类调用方法

2024-10-02 06:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

请先阅读问题,然后再将其标记为副本!

这个问题是由许多人提出的,但几乎所有人都给出了相同的解决办法,我已经申请。
所以我有类TestCaseBCD&;E
C&;D继承类B&;类E继承二者C&;D。类B继承TestCase

当我运行代码时,类E只与类C的方法一起运行,并且一直忽略D
现在我的课是这样的

class GenericAuthClass(TestCase):

    def setUp(self):
        """Create a dummy user for the purpose of testing."""
        # set some objects and variabels

    def _get_authenticated_api_client(self):
        pass

class TokenAuthTests(GenericAuthClass):

    def _get_authenticated_api_client(self):
        """Get token recieved on login."""
        super()._get_authenticated_api_client()
        # make object
        return object

class BasicAuthTests(GenericAuthClass):

    def _get_authenticated_api_client(self):
        """Get token recieved on login."""
        super()._get_authenticated_api_client()
        # make object
        return object

class ClientTestCase(BasicAuthTests, TokenAuthTests):
    def dothis(self):
        return self._get_authenticated_api_client()
  1. 如何调用C中的方法(使用相同的名称)和E中的D,就像C++中的菱形问题一样?到目前为止,当我从E使用self.method()调用某个方法时,它只从C调用该方法,而忽略了从D调用的同一个方法,而我认为它应该同时调用这两个方法。请注意,该方法在类E中不存在,我的代码现在运行正常,没有错误,只是从C调用了该方法。你知道吗

This seems like a Python question mainly but tagging django too as TestCase class might have something to do with it.


Tags: 方法代码selfclientapigetreturnobject
1条回答
网友
1楼 · 发布于 2024-10-02 06:38:48

This answer是正确的

you have to use something like a common base class to terminate the chain of super calls.

这意味着您需要编写自己的基类,该基类位于BC之间,并且TestCase通过实现附加方法结束super链,然后不将任何调用委派给其父类:

from django.test import TestCase

class MyTestBase(TestCase):
    def method1(self, arg):
        pass
    def method2(self, arg1, arg2):
        pass

class B(MyTestBase):
    def method1(self, arg):
        super().method1(arg)
        ...
    def method2(self, arg1, arg2):
        super().method2(arg1, arg2)
        ...

class C(MyTestBase):
    def method1(self, arg):
        super().method1(arg)
        ...
    def method2(self, arg1, arg2):
        super().method2(arg1, arg2)
        ...

class D(B, C):
    pass

相关问题 更多 >

    热门问题