Python—global vs local variables

本文探讨了Python编程中全局变量和局部变量的区别与使用场景,通过实例展示了它们在函数内外的不同行为,帮助理解这两类变量的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# num1 is a global variable


num1 = 1
print num1


# num2 is a local variable


def fun():
    num1 = 2
    num2 = num1 + 1
    print num2
    
fun()


# the scope of global num1 is the whole program, num 1 remains defined
print num1


# the scope of the variable num2 is fun(), num2 is now undefined
print num2

结果:

1
3
1
 NameError: name 'num2' is not defined


example2:

num = 4

def fun1():
    global num
    num = 5
    
def fun2():
    global num
    num = 6

# note that num changes after each call with no obvious explanation    
print num
fun1()
print num
fun2()
print num


结果:

4
5
6

在函数外定义的是全局变量,函数内部定义的是局部变量。如果全局变量在函数中使用了并更改了其值,则会生成一个同名的局部变量。所以在函数中引用全局变量并改变其值,要加上global关键字。


### Globalscope 与 Localscope 的区别 在编程中,作用域(Scope)决定了变量或其他标识符的有效范围。以下是关于 **Globalscope** 和 **Localscope** 的主要区别的详细介绍: #### 1. 定义 - **Global Scope**: 变量在整个程序生命周期内都可用,并可以在任何地方访问[^2]。通常情况下,这些变量是在文件级别或模块外部声明的。 - **Local Scope**: 变量仅在其所在的作用域内部有效,通常是某个特定函数或代码块内的变量。 #### 2. 生命周期 - **Global Variables**: 声明后一直存在直到程序结束。它们可以被多个函数共享并修改。 - **Local Variables**: 当其所在的函数调用完成时会被销毁。如果再次调用该函数,则会创建新的实例。 #### 3. 初始化行为 对于静态局部变量 (Static Local Variables),即使位于本地范围内,也只会在第一次初始化时赋值一次之后保持不变除非手动更改它: ```c++ #include <iostream> using namespace std; void exampleFunction() { static int counter = 0; // This will retain its value between calls. cout << "Counter is now: " << ++counter << endl; } int main(){ exampleFunction(); // Output: Counter is now: 1 exampleFunction(); // Output: Counter is now: 2 } ``` #### 4. 访问权限 - 在某些语言里比如C++ 或 Java 中,默认情况下的类成员如果没有指定访问修饰符的话将是私有的(private), 而全局对象一般公开(public). #### 5. 使用场景 虽然命名惯例有助于区分不同种类的数据项(如 'l_'代表local,'g_'代表global)[^1],但是为了减少错误发生率还是应该通过限定词来明确表达意图而不是单纯依赖于名称本身. 综上所述,Globalscope 提供了一个更广泛可触及性的环境,而Localscope 则限定了较小区域从而提高了安全性减少了冲突可能性. ```python def outer_function(): global_var = "I am accessible everywhere!" # Global variable declaration inside function def inner_function(): local_var = "Accessible only here." # Local variable limited by this block print(global_var) # Can access the global one from nested levels too try: print(local_var) except NameError as e: pass # Expected since out of scope when calling directly below inner_function() print(global_var) # Works fine because declared at top level even though defined under funciton context initially try: print(local_var) except UnboundLocalError as ue: pass # Fails due lack accessibility beyond defining boundary ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值