【发布时间】:2013-10-03 06:20:04
【问题描述】:
我有以下代码。
class Foo(object):
def __init__(self):
self.__baz = 40
def foo(self):
print self.__baz
class Bar(Foo):
def __init__(self):
#super(Bar, self).__init__()
self.__baz = 21
def bar(self):
print self.__baz
x = Bar()
x.foo()
x.bar()
我收到此错误:
Traceback (most recent call last):
File "classes.py", line 15, in <module>
x.foo()
File "classes.py", line 5, in foo
print self.__baz
AttributeError: 'Bar' object has no attribute '_Foo__baz'
为什么foo 方法没有在Bar 中继承。
编辑:如果你调用 super 被注释掉,它工作正常。
【问题讨论】:
-
不确定,但不是因为 __variablename 是一个特殊变量吗? stackoverflow.com/a/1301369/2537322
-
更奇怪的是,如果你打电话给
super(),为什么它工作? -
不是答案,但会添加更多详细信息 - 如果您将其从
__baz更改为baz,则两个调用都将打印 21。如果您调用super()并保留为__baz,则它们会打印 @987654332分别是@和21。
标签: python oop inheritance