I have two functions: functionA
and functionB
and I would like to call functionB
inside functionA
and pass to it all local variables defined in functionA
(and in the other way). For example I would like to make the below code works:
def functionA():
localA = 20
functionB()
print(localB)
def functionB():
print(localA)
localB=10
functionA()
Pass the local variables of functionA
as parameters to functionB
. Return the local variables of functionB
to functionA
:
def functionA():
localA = 20
localB = functionB(localA)
print(localB)
def functionB(localA):
print(localA)
localB = 10
return localB
I'm not sure if what you want to do is the ideal solution, but perhaps you could try something like this:
def functionB(local_vars):
print(local_vars["localA"])
def functionA():
localA = 20
local_vars = {k: v for k, v in locals().items() if not k.startswith('_')}
functionB(local_vars)
If there's much information that the two functions need to share, I would suggest encapsulating the what they're doing in combination into a class and making all the local variables that need to shared instance attributes prefixed with self.
.
Here's what I mean:
class ComboFuncs:
def functionA(self):
self.localA = 20
self.functionB()
print(self.localB)
def functionB(self):
print(self.localA)
self.localB = 10
ComboFuncs().functionA()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.