ขอบเขตและฟังก์ชันที่ผู้ใช้กำหนดเอง

Python เบื้องต้น: การเขียนฟังก์ชัน

Hugo Bowne-Anderson

Instructor

ทำความรู้จัก Scope ในฟังก์ชัน

  • ไม่ใช่ทุก object ที่เข้าถึงได้จากทุกที่ในสคริปต์

  • ขอบเขต (Scope) — ส่วนของโปรแกรมที่ object หรือชื่อนั้นเข้าถึงได้

    • Global scope — กำหนดในส่วนหลักของสคริปต์

    • Local scope — กำหนดภายในฟังก์ชัน

    • Built-in scope — ชื่อใน module built-ins ที่กำหนดไว้ล่วงหน้า

Python เบื้องต้น: การเขียนฟังก์ชัน

Global vs. Local Scope (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
Python เบื้องต้น: การเขียนฟังก์ชัน

Global vs. Local Scope (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
Python เบื้องต้น: การเขียนฟังก์ชัน

Global vs. Local Scope (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
Python เบื้องต้น: การเขียนฟังก์ชัน

Global vs. Local Scope (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
Python เบื้องต้น: การเขียนฟังก์ชัน

มาฝึกกันเถอะ!

Python เบื้องต้น: การเขียนฟังก์ชัน

Preparing Video For Download...