【发布时间】:2017-07-26 00:50:30
【问题描述】:
如何在子类的重写方法中访问超类方法的局部变量?
class Foo(object):
def foo_method(self):
x = 3
class Bar(Foo):
def foo_method(self):
super().foo_method()
print(x) # Is there a way to access x, besides making x an attribute of the class?
下面的代码给出了NameError: name 'x' is not defined
bar = Bar()
bar.foo_method()
这不足为奇,可以通过将x 设为实例属性来解决此问题,但是否可以更直接地在Bar.foo_method 中直接访问x?
【问题讨论】:
-
你不能那样做。为什么需要?
-
我不需要这样做。我只是想知道这是否可能。通常当 Python 的一个特性很难找到时,就意味着有更好的方法来做。
-
理论上,您不应该知道类/方法的内部工作原理,除非它专门将它们公开为公共属性。
标签: python python-3.x scope namespaces stack-frame