考虑这样的代码片段:
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
有人能帮助我理解这种行为吗?它与列表理解和类对象的范围有关吗?
PS C:fooProjects> & C:/Python38/python.exe c:/fooProjects/tmp.py
> c:fooprojectstmp.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
,则必须在interact
之前运行str_list = []
,然后在interact
中向列表添加内容。