小编Ale*_*dro的帖子

访问覆盖的父方法的局部变量

如何在子类的重写方法中访问超类方法的局部变量?

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吗?

python scope namespaces stack-frame python-3.x

3
推荐指数
1
解决办法
831
查看次数

标签 统计

namespaces ×1

python ×1

python-3.x ×1

scope ×1

stack-frame ×1