【问题标题】:Initialization of Multiple Inheritance in PythonPython中多重继承的初始化
【发布时间】:2020-07-30 12:56:52
【问题描述】:

我遇到了以下 python 代码,其中一个类继承自两个父类。我正在尝试了解该类的构造函数。

# wrapper.py:
#############
class EWrapper:
    def __init__(self):
        pass

...

# client.py
###########
class EClient(object):
    def __init__(self, wrapper):
        self.msg_queue = queue.Queue()
        self.wrapper = wrapper
        self.decoder = None
        self.reset()
....

# Test.py
#########
class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

有人可以详细说明EClient.__init__(self, self)吗?我不清楚两个selfs 的用法。 python怎么知道哪个self是哪个?

TestApp的对象构造过程是怎样的?

【问题讨论】:

  • 你能澄清你的问题吗? “python如何知道哪个自我是哪个?”是什么意思?只有一个对象绑定到所有自名。名称 self 与所有其他变量名称一样工作。
  • 一般来说,类的命名意味着 Wrapper 应该包含一个客户端,而不是一个客户端。在这里,组合可能比继承更合适。

标签: python class multiple-inheritance


【解决方案1】:

在初始化TestApp 时,您使用的是EWrapperself,然后是EClient,因为这是在类中定义的顺序。

【讨论】:

    【解决方案2】:

    在调用EClient.__init__(self, self) 中,第一个self 成为EClientdef __init__(self, wrapper): 中的EClient。接下来,如您所见,第二个self 在该调用中绑定到wrapperTestApp 继承了 EWrapper,因此它将自己用作 wrapperEClient

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      相关资源
      最近更新 更多