为什么我在 pdb 内无法访问 self.<method>

kkg*_*arg 2 python scope pdb

考虑这样的代码片段:

class ABC:
    def method1(self, word):
             ...

    def method2(self):
        str_list = ['this', 'is', 'a', 'list', 'of', 'strings']
        pdb.set_trace()
        str_list = [self.method1(word) for word in str_list] ...(1)

obj = ABC()
obj.method2()
Run Code Online (Sandbox Code Playgroud)

在断点处,当我将命令复制粘贴(1)到 pdb 调试器 shell 中时,它无法执行该命令,而是给出了错误:

*** NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我理解这种行为 - 它与列表理解和类对象的范围有关吗?


PS C:\fooProjects> & C:/Python38/python.exe c:/fooProjects/tmp.py
> c:\fooprojects\tmp.py(38)method2()
-> str_list = [self.method1(word) for word in str_list]
(Pdb) [self.method1(word) for word in str_list]
*** NameError: name 'self' is not defined
(Pdb)
Run Code Online (Sandbox Code Playgroud)

use*_*ica 5

在列表理解中,除了最外层可迭代的表达式之外的所有内容都在新范围中运行。您在 PDB 提示符处输入的代码将使用 执行exec,并且在内部创建的新作用域exec无法访问闭包变量,这self将是。

使用命令interact并编写常规for循环而不是列表推导式可以避免此范围问题。但是,interact创建了自己的新命名空间,并且在该命名空间内执行的变量分配不会传播回原始命名空间,因此如果要将新列表分配给 ,则str_list必须str_list = [] interact运行,然后将内容添加到列表中在interact