python - Function declaring global variable doesn't work in debug mode
问题描述
I'm debugging a program. In the debug console, I decided to write the following function:
def func():
global a
a=5
func()
a
a is undefined!
Why does this happens in the debug console?
解决方案
If you want to use a outside function, you should declare it first.
a = 0
def func():
global a
a=5
func()
print(a)
In this case will be 6 and 3
test=6
def func():
global test
print(test)
test=3
f()
print(test)
FYI: What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
推荐阅读
- c# - 如何在连接字符串位于数据库中的情况下触发迁移
- java - 错误:找不到符号方法 contextModule(ContextModule)
- python - 如何使用 Python 为 Django 编写竞赛条件的单元测试?
- python - 组合框函数 currentIndexChanged 无法正常工作
- java - 将 JdbcTemplate 与 CrudRepository 混合是否有意义?
- javascript - 如何为表单字段添加名称/如何引用 id [.module Drupal]?
- plsql - 如何在本地计算机上设置 PL/SQL 项目
- java - 编写一个程序,提示输入三角形的边长并报告三个角
- c# - 类未定义
- android - 在 Android 9.0 中未获取用户拨打的号码即使我在运行时也声明了读取通话记录和读取电话状态权限