来源:python中国网 时间:2020-03-15

  大家知道,可变类型全局变量可以在函数内部直接使用,比如一个列表可以在函数内部增删改查元素!如下;

# -*- coding: utf-8 -*-

nums = [1,2,3,4]

def change():
    nums.append('aaa')
    nums[1] = 'bbb'
    print(nums,id(nums))
change()
print(nums,id(nums))
[1, 'bbb', 3, 4, 'aaa'] 1923047722696
[1, 'bbb', 3, 4, 'aaa'] 1923047722696


  但是,如果你按照如下方式写?就会发现一旦在函数内部定义了同名变量,不管是写在第几行的,函数内部在使用一个变量时都会优先用函数内部定义的(js里面也有类似现象),所以才会有以下错误!

# -*- coding: utf-8 -*-

nums = [1,2,3,4]
def change():
    nums.append('aaa')
    nums = 123
change()
Traceback (most recent call last):
  File "D:/pyscript/py3script/ceshi.py", line 7, in 
    change()
  File "D:/pyscript/py3script/tieba_dziheng/ceshi.py", line 5, in change
    nums.append('aaa')
UnboundLocalError: local variable 'nums' referenced before assignment