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

Python v2.7.10的多重继承和变量访问问题,python,python-2.7,inheritance,multiple-inheritance,Python,Python 2.7,Inheritance,Multiple Inheritance,我想知道关于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__(

我想知道关于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'
回溯(最近一次呼叫最后一次):
文件“heritation.py”,第29行,在
fb.access()
access中第26行的文件“heritation.py”
self.deep_access()
文件“heritation.py”,第16行,在deep_access中
pp(自平衡杆)
AttributeError:“FooBar”对象没有属性“bar\u var”
从我收集的错误来看,它是在FooBar中查找bar_var,而不是bar,但是如果我调用父类,为什么不使用父类中声明的变量呢??如何让父类访问它自己的变量?对我来说,从一个不同的面向对象的方法来看,这似乎很奇怪


它尝试了
Bar.deep\u-access(self)
super(FooBar,self)。deep\u-access和
super(Bar,self)。deep\u-access
无效。

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

改变

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

等等


有一篇很好的文章解释了
super()
的大部分细节,名为

噢,上帝啊,哈哈。谢谢这是正确的答案。目前正在阅读的文章,看起来不错!
class Bar(Foo):
    def __init__(self):
        self.bar_var = 2
        super(Bar, self).__init__()
#             ^^^