我无法理解以下代码段的结果:my_str = "outside func"
def func():
my_str = "inside func"
class C():
print(my_str)
print((lambda:my_str)())
my_str = "inside C"
print(my_str)
输出为:
^{pr2}$
另一段代码是:my_str = "not in class"
class C:
my_str = "in the class"
print([my_str for i in (1,2)])
print(list(my_str for i in (1,2)))
输出为:[‘in the class’, 'in the class’]
['not in class’, 'not in class’]
问题是:在每个print()语句中发生了什么?在
有人能解释一下为什么print()语句从不同的名称空间获取字符串?在
编辑1:
我认为这与this question不同,因为我谦卑地认为那里的答案不能解释这种变化:my_str = "outside func"
def func():
my_str = "inside func"
class C():
print(my_str)
print((lambda:my_str)())
#my_str = "inside C"
print(my_str)
输出为:inside func
inside func
inside func
编辑2:
实际上,这是来自this question的复制品,因为正如Martijn Pieters所说:The answer there states: If a name is assigned to within a class body,
almost at the start. You assigned to my_str, making it the same case
as y there. Commenting out that line means you are no longer assigning
to my_str, making it the same case as x.