python - Access local variables of overridden parent method -


how can access local variables of super class method in overridden method in subclass?

class foo(object):     def foo_method(self):         x = 3  class bar(foo):     def foo_method(self):         super().foo_method()         print(x) # there way access x, besides making x attribute of class? 

the code below gives nameerror: name 'x' not defined

bar = bar() bar.foo_method() 

this isn't surprising, , can fixed making x instance attribute, can x accessed as-is in bar.foo_method more directly?

summary

q. ... can x accessed as-is in bar.foo_method more directly?

as written, the answer no.

by time super().foo_method() has returned, stack frame method has been wrapped-up , local variables gone. there nothing access.

alternative solution: return statement

the easiest solution sharing data have 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) 

alternative solution: dynamic scoping

if you're looking akin dynamic scoping, easiest solution pass in shared namespace:

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) 

if want simulate dynamic scoping in nested calls, consider using collections.chainmap().


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -