作用域

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

名稱

tom

Python 函式寫作

名稱

tom and janelle

Python 函式寫作

作用域

tom and janelle

Python 函式寫作

作用域

tom, janelle, and another tom

Python 函式寫作

作用域

x = 7
y = 200
print(x)
7
def foo():
    x = 42
    print(x)
    print(y)
foo()
42
200
print(x)
7
Python 函式寫作

作用域

scope_question

Python 函式寫作

作用域

local scope

Python 函式寫作

作用域

global scope

Python 函式寫作

作用域

builtin scope

Python 函式寫作

作用域

nonlocal scope

Python 函式寫作

關鍵字 global

x = 7

def foo():
  x = 42
  print(x)

foo()
42
print(x)
7
x = 7

def foo():
  global x
  x = 42
  print(x)

foo()
42
print(x)
42
Python 函式寫作

關鍵字 nonlocal

def foo():
  x = 10

  def bar():
    x = 200
    print(x)

  bar()
  print(x)

foo()
200
10
def foo():
  x = 10

  def bar():
    nonlocal x
    x = 200
    print(x)

  bar()
  print(x)

foo()
200
200
Python 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...