Python范围

变量只能在它创建的区域内使用。这称为范围


本地范围

在函数内部创建的变量属于该函数的局部范围,并且只能在该函数内部使用。

例子

在函数内部创建的变量在该函数内部可用:

def myfunc():
  x = 300
  print(x)

myfunc()
自己试试 »

函数里面的函数

如上例所述,该变量x在函数外部不可用,但对函数内部的任何函数都可用:

例子

可以从函数内的函数访问局部变量:

def myfunc():
  x = 300
  def myinnerfunc():
    print(x)
  myinnerfunc()

myfunc()
========
300

全局变量

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

myfunc()
print("Python is " + x)
------------------------------
#Python is fantastic
#Python is awesome

全局关键字

通常,当您在函数内部创建变量时,该变量是局部变量,并且只能在该函数内部使用。

要在函数内创建全局变量,可以使用 global关键字。

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

myfunc()
print("Python is " + x)
#------------------------
#要更改函数内的全局变量的值,请使用global关键字引用该变量:

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

myfunc()
print("Python is " + x)
#------------------------
#Python is fantastic
转载于:
https://www.w3schools.com/python/python_scope.asp

posted on 2022-03-28 15:36  -G  阅读(141)  评论(0)    收藏  举报

导航