如何在子类的重写方法中访问超类方法的局部变量?
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?
Run Code Online (Sandbox Code Playgroud)
下面的代码给出了 NameError: name 'x' is not defined
bar = Bar()
bar.foo_method()
Run Code Online (Sandbox Code Playgroud)
这不足为奇,可以通过创建x实例属性来修复它,但是可以x直接访问Bar.foo_method吗?