1)加上global x
,则函数内部引用的x
就是全局x
了
x = 1
def test():
global x
x = 2
print(x)
test() #2
print(x) #2
Code language: PHP (php)
(2)否则的话,变量名在等号左边,且在变量域内首次出现,
就认为是在定义局部变量。
x = 1
def test():
x = 2
print(x)
test() #2
print(x) #1
Code language: PHP (php)
(3)函数中如果定义了同名变量,就会覆盖对全局变量的引用
在局部变量赋值前使用变量会报错,即使外层有同名变量
UnboundLocalError: local variable 'x' referenced before assignment
Code language: JavaScript (javascript)
x = 1
def test():
print(x) #Error
x = 2
print(x)
test()
print(x)
Code language: PHP (php)
简书
https://www.jianshu.com/p/c3587a5f9f68
了解 Starx's Home 的更多信息
Subscribe to get the latest posts sent to your email.
0 条评论