在Python 3.6.x及更高版本中,有一种方法可以引用(询问)函数中包含的局部变量,该局部变量在调用堆栈中比需要执行查询的函数要高-而无需将变量传递为争论?
例如:
def lowest_leaf():
#Is there a way to access a_value and/or b_value
#from lowest_leaf() WITHOUT passing them as arguments into
#this function?
#HERE: print(a_value)
#HERE: print(b_value)
return(0)
def middle_leaf(a_value):
print(a_value)
b_value = a_value * 2
lowest_leaf()
return(0)
def root_leaf():
a_value = 10
middle_leaf(a_value)
return(0)
if '__name__' == '__main__':
root_leaf()
很多,很多感谢您的帮助!
答案 0 :(得分:1)
我要强调的是,这通常是一件狡猾的事情,因为它破坏了封装,如评论中所述。除非您有充分的理由这样做(并且如果您需要考虑是否这样做,您不要),我建议您重新设计应用程序。
尽管如此,Python是基于我们都同意成年人的想法而建立的,因此,您可以使用inspect
做您想做的事情:
import inspect
def lowest_leaf():
middle_leaf_frame = inspect.currentframe().f_back
print(middle_leaf_frame.f_locals)
root_leaf_frame = middle_leaf_frame.f_back
print(root_leaf_frame.f_locals)
def middle_leaf(a_value):
b_value = a_value * 2
lowest_leaf()
def root_leaf():
a_value = 10
middle_leaf(a_value)
root_leaf()
输出:
{'a_value': 10, 'b_value': 20}
{'a_value': 10}
答案 1 :(得分:0)
不确定这是否有帮助,但这是我看到目标得以实现的唯一方法。 基本上,我们定义了一个类。
class tree:
def __init__(self):
pass
def lowest_leaf(self):
#Is there a way to access a_value and/or b_value
#from lowest_leaf() WITHOUT passing them as arguments into
#this function?
#HERE: print(a_value)
#HERE: print(a_value)
print(self.a_value)
print(self.b_value)
return(0)
def middle_leaf(self,a_value):
self.b_value = a_value * 2
self.lowest_leaf()
return(0)
def root_leaf(self):
self.a_value = 10
self.middle_leaf(self.a_value)
return(0)
tree1 = tree() # we define the tree here
tree1.root_leaf() # we can run any method we want.
输出:
10
20