简体   繁体   English

如何逐步检查python代码以查找何时修改了变量?

[英]How can I step through python code to find when a variable is modified?

I am writing a python program which defines a class, SpatialPooler. 我正在编写一个定义类SpatialPooler的python程序。 Objects of this class have an internal Boolean variable, self._learn and another internal variable self._data. 此类的对象具有内部布尔变量self._learn和另一个内部变量self._data。 When self._learn==False, self._data should not be altered by the SpatialPooler's main method. 当self._learn ==假,self._data 应该由SpatialPooler的主要方法改变。

I have another python file which creates an object instantiating this class and then runs through a test scenario. 我还有另一个python文件,该文件创建实例化此类的对象,然后运行测试场景。 With learning turned on, the output is as expected. 启用学习后,输出将达到预期。 However, when learning is turned off, something goes wrong and self._data is modified, but I cannot find where in the code this is happening. 但是,当学习被关闭时,出了点问题,self._data被修改了,但是我找不到在代码中发生的地方。

Is there a way to step through the code to find where this variable is being modified? 有没有一种方法可以逐步检查代码以查找在哪里修改了此变量? pdb seems like it may be the kind of tool that would allow me to do this, but my code is not actually throwing any warnings or errors, and I can't find any instructions on how I could accomplish finding the function that is inappropriately modifying the self._data variable. pdb似乎是一种允许我执行此操作的工具,但是我的代码实际上并未引发任何警告或错误,并且我找不到关于如何完成查找不适当修改的功能的任何说明。 self._data变量。

Any suggestions or tips would be much appreciated. 任何建议或技巧将不胜感激。

It's a little difficult to tell you where exactly to put this, but you can add a pdb statement somewhere in the code. 告诉您确切的位置是很困难的,但是您可以在代码中的某处添加一个pdb语句。

Specifically, add import pdb; pdb.set_trace() 具体来说,添加import pdb; pdb.set_trace() import pdb; pdb.set_trace() somewhere in the code (maybe the main function you mentioned), and when the program gets to that line, it will go into the debugger. import pdb; pdb.set_trace()在代码中的某个位置(可能是您提到的主要功能),并且当程序到达该行时,它将进入调试器。 You can then step through the code as it executes (by entering n ). 然后,您可以逐步执行代码(输入n )。 You can see what the variable values are by just typing the variable name ( self._data , if you're in the class's method). 您只需输入变量名称即可看到变量值( self._data ,如果您使用的是类的方法)。

Reference to how pdb is used. 参考如何使用pdb。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM