Phạm vi và hàm do người dùng định nghĩa

Giới thiệu về Functions trong Python

Hugo Bowne-Anderson

Instructor

Tóm tắt nhanh về phạm vi trong hàm

  • Không phải mọi đối tượng đều truy cập được ở mọi nơi trong script

  • Phạm vi (scope) - phần chương trình nơi một đối tượng hoặc tên có thể truy cập

    • Phạm vi toàn cục (global) - định nghĩa trong thân chính của script

    • Phạm vi cục bộ (local) - định nghĩa bên trong hàm

    • Phạm vi dựng sẵn (built-in) - các tên trong mô-đun builtins dựng sẵn

Giới thiệu về Functions trong Python

Phạm vi toàn cục vs. cục bộ (1)

def square(value):
    """Returns the square of a number."""
    new_val = value ** 2
    return new_val

square(3)
9
new_val
<hr />----------------------------------------------------------------
NameError                       Traceback (most recent call last)
<ipython-input-3-3cc6c6de5c5c> in <module>()
<hr />-> 1 new_value
NameError: name 'new_val' is not defined
Giới thiệu về Functions trong Python

Phạm vi toàn cục vs. cục bộ (2)

new_val = 10

def square(value):
    """Returns the square of a number."""
    new_val = value ** 2
    return new_val

square(3)
9
new_val
10
Giới thiệu về Functions trong Python

Phạm vi toàn cục vs. cục bộ (3)

new_val = 10

def square(value):
    """Returns the square of a number."""
    new_value2 = new_val ** 2
    return new_value2

square(3)
100
new_val = 20

square(new_val)
400
Giới thiệu về Functions trong Python

Phạm vi toàn cục vs. cục bộ (4)

new_val = 10

def square(value):
    """Returns the square of a number."""
    global new_val
    new_val = new_val ** 2
    return new_val

square(3)
100
new_val
100
Giới thiệu về Functions trong Python

Hãy thực hành!

Giới thiệu về Functions trong Python

Preparing Video For Download...