为什么我在 pdb 中无法访问 self.<method>
Why I can't access self.<method> while inside 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()
在断点处,当我在 pdb 调试器 shell 中复制粘贴命令 (1)
时,它无法执行命令,而是给我错误:
*** NameError: name 'self' is not defined
任何人都可以帮助我理解这种行为 - 它是否与列表理解和 class 对象的范围有关?
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)
在列表理解中,除了最外层可迭代 运行 的表达式之外的所有内容都在新范围内。您在 PDB 提示符下输入的代码使用 exec
执行,并且在 exec
中创建的新作用域无法访问闭包变量,而 self
可以。
使用 interact
命令并编写常规 for
循环而不是列表理解将避免此范围问题。但是,interact
创建了自己的新命名空间,并且在该命名空间内执行的变量赋值不会传播回原始命名空间,因此如果您想将新列表分配给 str_list
,您需要到 运行 str_list = []
before interact
然后将内容添加到 interact
.
中的列表
考虑这样的代码片段:
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()
在断点处,当我在 pdb 调试器 shell 中复制粘贴命令 (1)
时,它无法执行命令,而是给我错误:
*** NameError: name 'self' is not defined
任何人都可以帮助我理解这种行为 - 它是否与列表理解和 class 对象的范围有关?
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)
在列表理解中,除了最外层可迭代 运行 的表达式之外的所有内容都在新范围内。您在 PDB 提示符下输入的代码使用 exec
执行,并且在 exec
中创建的新作用域无法访问闭包变量,而 self
可以。
使用 interact
命令并编写常规 for
循环而不是列表理解将避免此范围问题。但是,interact
创建了自己的新命名空间,并且在该命名空间内执行的变量赋值不会传播回原始命名空间,因此如果您想将新列表分配给 str_list
,您需要到 运行 str_list = []
before interact
然后将内容添加到 interact
.