gpt4 book ai didi

python - 检索/打印执行上下文

转载 作者:行者123 更新时间:2023-11-28 17:55:11 27 4
gpt4 key购买 nike

编辑:这个问题已经在 apphacker 和 ConcernedOfTunbridgeWells 的帮助下得到解决。我已更新代码以反射(reflect)我将使用的解决方案。

我目前正在编写一个群体智能模拟器,希望为用户提供一种调试算法的简便方法。在其他输出中,我觉得在算法的每个步骤开始时为用户提供执行上下文的打印输出会很有帮助。

下面的代码实现了我所需要的。

import inspect

def print_current_execution_context():
frame=inspect.currentframe().f_back #get caller frame
print frame.f_locals #print locals of caller

class TheClass(object):
def __init__(self,val):
self.val=val
def thefunction(self,a,b):
c=a+b
print_current_execution_context()


C=TheClass(2)
C.thefunction(1,2)

这给出了预期的输出:

{'a': 1, 'c': 3, 'b': 2, 'self': <__main__.TheClass object at 0xb7d2214c>}

感谢 apphacker 和 ConcernedOfTunbridgeWells 向我指出了这个答案

最佳答案

尝试:

class TheClass(object):
def __init__(self,val):
self.val=val
def thefunction(self,a,b):
c=a+b
print locals()


C=TheClass(2)
C.thefunction(1,2)

关于python - 检索/打印执行上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/750702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com