访问重写的父方法的局部变量

Access local variables of overridden parent method

如何在 subclass 的覆盖方法中访问 super class 方法的局部变量?

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 成为实例属性来解决这个问题,但是 x 可以在 Bar.foo_method 中更直接地按原样访问吗?

总结

Q. ... can x be accessed as-is in Bar.foo_method more directly?

正如所写,答案是否定的

super().foo_method() 已 returned 时,该方法的堆栈帧已结束,局部变量已消失。没有可访问的内容。

备选方案:return语句

共享数据最简单的解决方案是 foo_method return x:

class Foo(object):
    def foo_method(self):
        x = 3
        return x

class Bar(Foo):
    def foo_method(self):
        x = super().foo_method()
        print(x)

替代解决方案:动态范围

如果您正在寻找类似于 dynamic scoping 的内容,最简单的解决方案是传入共享命名空间:

class Foo(object):
    def foo_method(self, ns):
        x = 3
        ns['x'] = 3

class Bar(Foo):
    def foo_method(self):
        ns = {}
        super().foo_method(ns)
        x = ns['x']
        print(x)

如果您想在嵌套调用中模拟动态范围,请考虑使用 collections.ChainMap()