作用域

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

名称

汤姆

Python 函数编写

名称

汤姆和贾内尔

Python 函数编写

作用域

汤姆和贾内尔

Python 函数编写

作用域

汤姆、贾内尔和另一位汤姆

Python 函数编写

作用域

x = 7
y = 200
print(x)
7
def foo():
    x = 42
    print(x)
    print(y)
foo()
42
200
print(x)
7
Python 函数编写

作用域

作用域_问题

Python 函数编写

作用域

局部作用域

Python 函数编写

作用域

全局作用域

Python 函数编写

作用域

内建作用域

Python 函数编写

作用域

非局部作用域

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 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...