Python v2.7.10 的多重继承和变量访问问题

Multiple Inheritance and variable access issue with Python v2.7.10

我想知道 Python 遇到的这个问题,我相信这是众所周知的。我已经涉足 Python 一段时间了,我已经习惯了它的味道,但我正在 运行 解决下面概述的这个问题。如果您 运行 以下代码:

import pprint
pp = pprint.PrettyPrinter(indent=4).pprint


class Foo(object):
    def __init__(self):
        self.foo_var = 1


class Bar(Foo):
    def __init__(self):
        self.bar_var = 2
        super(Foo, self).__init__()

    def deep_access(self):
        pp(self.bar_var)


class FooBar(Bar):
    def __init__(self):
        self.foobar_var = 3
        super(Bar, self).__init__()

    def access(self):
        # call Bar
        self.deep_access()

fb = FooBar()
fb.access()

您将收到以下错误:

Traceback (most recent call last):
  File "inheritance.py", line 29, in <module>
    fb.access()
  File "inheritance.py", line 26, in access
    self.deep_access()
  File "inheritance.py", line 16, in deep_access
    pp(self.bar_var)
AttributeError: 'FooBar' object has no attribute 'bar_var'

根据我收集到的错误,它在 FooBar 而不是 Bar 中寻找 bar_var,但是如果我调用父 class,为什么不使用在父中声明的变量?如何让父 class 访问它自己的变量?来自不同的 OOP 方法对我来说似乎很奇怪。

它尝试了 Bar.deep_access(self)super(FooBar, self).deep_access 以及 super(Bar, self).deep_access 而不是 self.deep_access 但它不起作用。

您没有正确调用 super()。第一个参数应该始终是class,它是调用 super,而不是它的任何基础classes..

改变

class Bar(Foo):
    def __init__(self):
        self.bar_var = 2
        super(Foo, self).__init__()
#             ^^^

class Bar(Foo):
    def __init__(self):
        self.bar_var = 2
        super(Bar, self).__init__()
#             ^^^

等等...

有一篇很好的文章,解释了 super() 的大部分来龙去脉,叫做 "Super considered Super!"