在python中、关于全局变量和局部变量、以下_Python类和全局变量与局部变量

我无法理解以下代码段的结果: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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值