Python2/ python3 accessing and overwriting variables in nested functions

对比

In Python 3.x,

内部函数可以对外部函数中的局变量进行访问,但不能对他进行修改

如果想修改,you can use the nonlocal keyword:

def outer():
    string = ""
    def inner():
        nonlocal string
        string = "String was changed by a nested function!"
    inner()
    return string
# 也不能写成:
# nonlocal string
#         string = "String was changed by a nested function!"
# 否则会报错 ,同global关键字的使用一样

In Python 2.x,

内部函数不能对外部函数中的局变量进行访问,也不能修改

如果想访问和修改,you could

(1) use a list with a single element and overwrite that single element:

def outer():
    string = [""]
    def inner():
        string[0] = "String was changed by a nested function!"
    inner()
    return string[0]

(2)use global keword

 

Python2 - Global Variables

❮ PreviousNext ❯


Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable inside a function, with the same name as the global variable

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

运行结果:

Python is fantastic
Python is awesome

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x


# 注意不能直接在初始化的时候加global关键词,否则会报错
# SyntaxError: invalid syntax
#    global x = "ss"

运行结果:

Python is fantastic

Also, use the global keyword if you want to change a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

运行结果:

Python is fantastic

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值