python - Python中的任何类型的范围解析运算符?
问题描述
当还有一个同名的局部变量时,有什么办法可以让python解释器专门选择全局变量?(就像 C++ 有 :: 运算符)
x=50
def fun():
x=20
print("The value of local x is",x)
global x
#How can I display the value of global x here?
print("The value of global x is",x)
print("The value of global x is",x)
fun()
功能块内的第二个打印语句应显示全局 x 的值。
File "/home/karthik/PycharmProjects/helloworld/scope.py", line 7
global x
^
SyntaxError: name 'x' is used prior to global declaration
Process finished with exit code 1
解决方案
Python 没有直接等价于::
运算符(通常这种事情由 dot 处理.
)。要从外部范围访问变量,请将其分配给不同的名称以不隐藏它:
x = 50
def fun():
x = 20
print(x) # 20
print(x_) # 50
print(x) # 50
x_ = x
fun()
但是,如果没有对此进行破解,Python当然不会是Python......你所描述的实际上是可能的,但我不推荐它:
x = 50
def fun():
x = 20
print(x) # 20
print(globals()['x']) # 50
print(x) # 50
fun()
推荐阅读
- selenium - 执行 selenium 脚本的替代方法
- expo - 无法启动 Expo CLI
- javascript - 如果值存在,则对对象数组进行排序
- android - Android Gradle Protobufs:如何编译完整的 protobuf 而不是“lite”版本?
- java - 为什么在注释中禁止 null 作为默认值?
- terraform - 在 API Gateway 资源中创建可变数量的方法和资源
- r - 使用 knitr 和 Lyx 为 R 代码块添加行号
- java - 解析后某些 unicode 字符作为其 HTML 代码返回
- php - 从 PHP 表单向 Web 服务 Rest 发送数据,并将其保存在 MySQL 数据库中
- java - 如何在 @Controller @RequestMapping 生效之前检索 URL?