Hướng dẫn what is scope of object in python? - phạm vi đối tượng trong python là gì?


Một biến chỉ có sẵn từ bên trong khu vực nó được tạo ra. Đây được gọi là phạm vi.scope.

Show

Phạm vi địa phương

Một biến được tạo bên trong một hàm thuộc phạm vi cục bộ của hàm đó và chỉ có thể được sử dụng bên trong hàm đó.

Thí dụ

Một biến được tạo bên trong một hàm có sẵn bên trong chức năng đó:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)
  x = 300
  print(x)

myfunc()

Hãy tự mình thử »

Chức năng bên trong chức năng

Như đã giải thích trong ví dụ trên, biến

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:

Thí dụ

Một biến được tạo bên trong một hàm có sẵn bên trong chức năng đó:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)
  x = 300
  def myinnerfunc():
    print(x)
  myinnerfunc()

myfunc()

Hãy tự mình thử »



Chức năng bên trong chức năng

Như đã giải thích trong ví dụ trên, biến

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:

Biến cục bộ có thể được truy cập từ một hàm trong hàm:

Thí dụ

Một biến được tạo bên trong một hàm có sẵn bên trong chức năng đó:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)

Hãy tự mình thử »
  print(x)

myfunc()

print(x)

Chức năng bên trong chức năng

Như đã giải thích trong ví dụ trên, biến >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:

Biến cục bộ có thể được truy cập từ một hàm trong hàm:

Thí dụ

Một biến được tạo bên trong một hàm có sẵn bên trong chức năng đó:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)

Hãy tự mình thử »
  x = 200
  print(x)

myfunc()

print(x)

Chức năng bên trong chức năng


Như đã giải thích trong ví dụ trên, biến >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:

Biến cục bộ có thể được truy cập từ một hàm trong hàm:

def myfunc (): & nbsp; x = 300 & nbsp; def myinnerfunc (): & nbsp; & nbsp; in (x) & nbsp; myinnerfunc ()

Thí dụ

Một biến được tạo bên trong một hàm có sẵn bên trong chức năng đó:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)
  global x
  x = 300

myfunc()

Hãy tự mình thử »

Chức năng bên trong chức năng

Như đã giải thích trong ví dụ trên, biến

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:

Thí dụ

Biến cục bộ có thể được truy cập từ một hàm trong hàm:

def myfunc (): & nbsp; x = 300 & nbsp; in (x)

Hãy tự mình thử »
  global x
  x = 200

myfunc()

Hãy tự mình thử »

Hãy tự mình thử »



Khái niệm về quy tắc phạm vi cách các biến và tên được tra cứu trong mã của bạn. Nó xác định khả năng hiển thị của một biến trong mã. Phạm vi của một tên hoặc biến phụ thuộc vào vị trí trong mã của bạn nơi bạn tạo biến đó. Khái niệm phạm vi Python thường được trình bày bằng cách sử dụng một quy tắc được gọi là Quy tắc LEGB.scope rules how variables and names are looked up in your code. It determines the visibility of a variable within the code. The scope of a name or variable depends on the place in your code where you create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule.

Các chữ cái trong từ viết tắt của LegB là các phạm vi địa phương, bao quanh, toàn cầu và tích hợp. Điều này tóm tắt không chỉ các cấp độ phạm vi Python mà còn cả chuỗi các bước mà Python theo sau khi giải quyết tên trong một chương trình.Local, Enclosing, Global, and Built-in scopes. This summarizes not only the Python scope levels but also the sequence of steps that Python follows when resolving names in a program.

Trong hướng dẫn này, bạn sẽ học:

  • Phạm vi là gì và cách chúng hoạt động trong Pythonscopes are and how they work in Python
  • Tại sao nó rất quan trọng để biết về phạm vi PythonPython scope
  • Quy tắc LegB là gì và cách Python sử dụng nó để giải quyết tênLEGB rule is and how Python uses it to resolve names
  • Cách sửa đổi hành vi tiêu chuẩn của phạm vi Python bằng cách sử dụng
    >>> square.__code__.co_varnames
    ('base', 'result')
    >>> square.__code__.co_argcount
    1
    >>> square.__code__.co_consts
    (None, 2, 'The square of ', ' is: ')
    >>> square.__code__.co_name
    'square'
    
    6 và
    >>> def outer_func():
    ...     # This block is the Local scope of outer_func()
    ...     var = 100  # A nonlocal var
    ...     # It's also the enclosing scope of inner_func()
    ...     def inner_func():
    ...         # This block is the Local scope of inner_func()
    ...         print(f"Printing var from inner_func(): {var}")
    ...
    ...     inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Printing var from outer_func(): 100
    >>> inner_func()
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'inner_func' is not defined
    
    2standard behavior of Python scope using
    >>> square.__code__.co_varnames
    ('base', 'result')
    >>> square.__code__.co_argcount
    1
    >>> square.__code__.co_consts
    (None, 2, 'The square of ', ' is: ')
    >>> square.__code__.co_name
    'square'
    
    6 and
    >>> def outer_func():
    ...     # This block is the Local scope of outer_func()
    ...     var = 100  # A nonlocal var
    ...     # It's also the enclosing scope of inner_func()
    ...     def inner_func():
    ...         # This block is the Local scope of inner_func()
    ...         print(f"Printing var from inner_func(): {var}")
    ...
    ...     inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Printing var from outer_func(): 100
    >>> inner_func()
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'inner_func' is not defined
    
    2
  • Những công cụ liên quan đến phạm vi mà Python cung cấp và cách bạn có thể sử dụng chúngscope-related tools Python offers and how you can use them

Với kiến ​​thức này trong tay, bạn có thể tận dụng phạm vi Python để viết các chương trình đáng tin cậy và có thể duy trì hơn. Sử dụng phạm vi Python sẽ giúp bạn tránh hoặc giảm thiểu các lỗi liên quan đến va chạm tên cũng như sử dụng xấu các tên toàn cầu trên các chương trình của bạn.

Bạn có thể tận dụng tối đa hướng dẫn này nếu bạn quen thuộc với các khái niệm Python trung gian như các lớp, chức năng, chức năng bên trong, biến, ngoại lệ, toàn diện, chức năng tích hợp và cấu trúc dữ liệu tiêu chuẩn.

Hiểu phạm vi

Trong lập trình, phạm vi của một tên xác định khu vực của một chương trình mà bạn có thể truy cập rõ ràng vào tên đó, chẳng hạn như các biến, hàm, đối tượng, v.v. Một tên sẽ chỉ được hiển thị và có thể truy cập bằng mã trong phạm vi của nó. Một số ngôn ngữ lập trình tận dụng phạm vi để tránh va chạm tên và hành vi không thể đoán trước. Thông thường nhất, bạn sẽ phân biệt hai phạm vi chung:scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on. A name will only be visible to and accessible by the code in its scope. Several programming languages take advantage of scope for avoiding name collisions and unpredictable behaviors. Most commonly, you’ll distinguish two general scopes:

  1. Phạm vi toàn cầu: Tên mà bạn xác định trong phạm vi này có sẵn cho tất cả các mã của bạn. The names that you define in this scope are available to all your code.

  2. Phạm vi cục bộ: Tên mà bạn xác định trong phạm vi này chỉ có sẵn hoặc hiển thị với mã trong phạm vi. The names that you define in this scope are only available or visible to the code within the scope.

Phạm vi xuất hiện bởi vì các ngôn ngữ lập trình sớm (như cơ bản) chỉ có tên toàn cầu. Với loại tên này, bất kỳ phần nào của chương trình đều có thể sửa đổi bất kỳ biến nào bất cứ lúc nào, vì vậy việc duy trì và gỡ lỗi các chương trình lớn đều có thể trở thành một cơn ác mộng thực sự. Để làm việc với các tên toàn cầu, bạn cần phải ghi nhớ tất cả các mã đồng thời để biết giá trị của một tên nhất định là gì bất cứ lúc nào. Đây là một tác dụng phụ quan trọng của việc không có phạm vi.global names. With this kind of name, any part of the program could modify any variable at any time, so maintaining and debugging large programs could become a real nightmare. To work with global names, you’d need to keep all the code in mind at the same time to know what the value of a given name is at any time. This was an important side-effect of not having scopes.

Một số ngôn ngữ như Python sử dụng phạm vi để tránh loại vấn đề này. Khi bạn sử dụng một ngôn ngữ thực hiện phạm vi, thì không có cách nào để bạn truy cập tất cả các biến trong một chương trình tại tất cả các vị trí trong chương trình đó. Trong trường hợp này, khả năng truy cập một tên nhất định của bạn sẽ phụ thuộc vào nơi bạn đã xác định tên đó.scope to avoid this kind of problem. When you use a language that implements scope, there’s no way for you to access all the variables in a program at all locations in that program. In this case, your ability to access a given name will depend on where you’ve defined that name.

Tên trong các chương trình của bạn sẽ có phạm vi của khối mã mà bạn xác định chúng. Khi bạn có thể truy cập giá trị của một tên nhất định từ nơi nào đó trong mã của bạn, bạn sẽ nói rằng tên nằm trong phạm vi. Nếu bạn có thể truy cập tên, thì bạn sẽ nói rằng tên nằm ngoài phạm vi.in scope. If you can’t access the name, then you’ll say that the name is out of scope.

Tên và phạm vi trong Python

Vì Python là một ngôn ngữ được gõ động, các biến trong Python ra đời khi bạn lần đầu tiên gán cho chúng một giá trị. Mặt khác, các chức năng và các lớp có sẵn sau khi bạn xác định chúng bằng cách sử dụng

>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
3 hoặc
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
4, tương ứng. Cuối cùng, các mô -đun tồn tại sau khi bạn nhập chúng. Tóm lại, bạn có thể tạo tên Python thông qua một trong các hoạt động sau:

Hoạt độngBản tường trình
Bài tập
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
5
HOẠT ĐỘNG HOẠT ĐỘNG
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
6 hoặc
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
7
Định nghĩa chức năng
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
8
Định nghĩa đối số trong bối cảnh của các chức năng
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
9
Định nghĩa lớp
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
0

Tất cả các hoạt động này tạo ra hoặc, trong trường hợp bài tập, cập nhật tên Python mới vì tất cả chúng gán tên cho một biến, không đổi, chức năng, lớp, thể hiện, mô -đun hoặc đối tượng Python khác.

Python sử dụng vị trí của gán hoặc định nghĩa tên để liên kết nó với một phạm vi cụ thể. Nói cách khác, nơi bạn gán hoặc xác định tên trong mã của bạn xác định phạm vi hoặc khả năng hiển thị của tên đó.

Ví dụ: nếu bạn gán một giá trị cho một tên bên trong một hàm, thì tên đó sẽ có phạm vi Python cục bộ. Ngược lại, nếu bạn gán một giá trị cho một tên bên ngoài tất cả các chức năng, nói rằng, ở cấp cao nhất của một mô -đun thì tên đó sẽ có phạm vi Python toàn cầu.local Python scope. In contrast, if you assign a value to a name outside of all functions—say, at the top level of a module—then that name will have a global Python scope.

Phạm vi Python vs không gian tên

Trong Python, khái niệm về phạm vi có liên quan chặt chẽ đến khái niệm về không gian tên. Như bạn đã học được cho đến nay, một phạm vi Python xác định vị trí trong chương trình của bạn có thể nhìn thấy tên của bạn. Phạm vi Python được triển khai dưới dạng từ điển ánh xạ tên cho các đối tượng. Những từ điển này thường được gọi là không gian tên. Đây là những cơ chế cụ thể mà Python sử dụng để lưu trữ tên. Họ được lưu trữ trong một thuộc tính đặc biệt gọi là

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1.namespaces. These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1.

Tên ở cấp cao nhất của một mô -đun được lưu trữ trong không gian tên mô -đun. Nói cách khác, họ đã lưu trữ trong thuộc tính mô -đun ____ ____61. Hãy xem mã sau:

>>>

>>> import sys
>>> sys.__dict__.keys()
dict_keys(['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2'])

Sau khi bạn nhập

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3, bạn có thể sử dụng
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
4 để kiểm tra các khóa của
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
5. Điều này trả về một danh sách với tất cả các tên được xác định ở cấp cao nhất của mô -đun. Trong trường hợp này, bạn có thể nói rằng
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 giữ không gian tên của
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3 và là một biểu diễn cụ thể của phạm vi mô -đun.

Ví dụ nữa, giả sử rằng bạn cần sử dụng tên

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
8, được định nghĩa trong
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3. Nếu bạn biết cách
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
8 theo ít nhất hai cách khác nhau:

  1. Sử dụng ký hiệu dấu chấm trên tên mô -đun trong mẫu
    >>> __name__
    '__main__'
    
    2
  2. Sử dụng hoạt động đăng ký trên
    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    1 ở dạng
    >>> __name__
    '__main__'
    
    4

Hãy xem mã sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '

Sau khi bạn nhập

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3, bạn có thể sử dụng
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
4 để kiểm tra các khóa của
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
5. Điều này trả về một danh sách với tất cả các tên được xác định ở cấp cao nhất của mô -đun. Trong trường hợp này, bạn có thể nói rằng
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 giữ không gian tên của
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3 và là một biểu diễn cụ thể của phạm vi mô -đun.

Ví dụ nữa, giả sử rằng bạn cần sử dụng tên

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
8, được định nghĩa trong
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
3. Nếu bạn biết cách
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo
>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
8 theo ít nhất hai cách khác nhau:

Sử dụng ký hiệu dấu chấm trên tên mô -đun trong mẫu >>> __name__ '__main__' 2

Sử dụng hoạt động đăng ký trên

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 ở dạng
>>> __name__
'__main__'
4LEGB rule, which is named after the Python scope for names. The letters in LEGB stand for Local, Enclosing, Global, and Built-in. Here’s a quick overview of what these terms mean:

  • Hãy xem mã sau: is the code block or body of any Python function or

    >>> dir()
    ['__annotations__', '__builtins__',..., '__package__', '__spec__']
    >>> var = 100  # Assign var at the top level of __main__
    >>> dir()
    ['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
    
    1 expression. This Python scope contains the names that you define inside the function. These names will only be visible from the code of the function. It’s created at function call, not at function definition, so you’ll have as many different local scopes as function calls. This is true even if you call the same function multiple times, or recursively. Each call will result in a new local scope being created.

  • Khi bạn đã nhập

    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    3, bạn có thể truy cập
    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    8 bằng cách sử dụng ký hiệu dấu chấm trên
    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    3. Bạn cũng có thể truy cập
    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    8 bằng cách sử dụng tra cứu khóa từ điển với khóa
    >>> __name__
    '__main__'
    
    9. Cả hai hành động trả về cùng một kết quả,
    >>> dir()
    ['__annotations__', '__builtins__',..., '__package__', '__spec__']
    >>> var = 100  # Assign var at the top level of __main__
    >>> dir()
    ['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
    
    0.
    is a special scope that only exists for nested functions. If the local scope is an inner or nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function. The names in the enclosing scope are visible from the code of the inner and enclosing functions.

  • Bất cứ khi nào bạn sử dụng tên, chẳng hạn như một biến hoặc tên hàm, Python tìm kiếm thông qua các cấp độ phạm vi khác nhau (hoặc không gian tên) để xác định xem tên có tồn tại hay không. Nếu tên tồn tại, thì bạn sẽ luôn có lần xuất hiện đầu tiên của nó. Nếu không, bạn sẽ gặp lỗi. Bạn sẽ bao gồm cơ chế tìm kiếm này trong phần tiếp theo. is the top-most scope in a Python program, script, or module. This Python scope contains all of the names that you define at the top level of a program or a module. Names in this Python scope are visible from everywhere in your code.

  • Sử dụng quy tắc LegB cho phạm vi Python is a special Python scope that’s created or loaded whenever you run a script or open an interactive session. This scope contains names such as keywords, functions, exceptions, and other attributes that are built into Python. Names in this Python scope are also available from everywhere in your code. It’s automatically loaded by Python when you run a program or script.

Python giải quyết các tên bằng cách sử dụng quy tắc được gọi là LEGB, được đặt tên theo phạm vi Python cho tên. Các chữ cái trong LegB là viết tắt của địa phương, bao quanh, toàn cầu và tích hợp. Ở đây, một cái nhìn tổng quan nhanh về những điều khoản này có nghĩa là gì:

Phạm vi cục bộ (hoặc chức năng) là khối mã hoặc phần thân của bất kỳ chức năng Python hoặc biểu thức

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
1 nào. Phạm vi Python này chứa các tên mà bạn xác định bên trong hàm. Những tên này sẽ chỉ hiển thị từ mã của hàm. Nó được tạo ra tại Call Function Call, không phải ở định nghĩa chức năng, do đó, bạn sẽ có nhiều phạm vi cục bộ khác nhau như các cuộc gọi chức năng. Điều này đúng ngay cả khi bạn gọi cùng một hàm nhiều lần hoặc đệ quy. Mỗi cuộc gọi sẽ dẫn đến một phạm vi địa phương mới được tạo ra.

Tại bất kỳ thời điểm nào trong quá trình thực hiện, bạn sẽ có nhiều nhất bốn phạm vi Python hoạt động, tính toán, bao quanh, toàn cầu và tích hợp phụ thuộc vào nơi bạn đang ở trong mã. Mặt khác, bạn sẽ luôn có ít nhất hai phạm vi hoạt động, đó là phạm vi toàn cầu và tích hợp. Hai phạm vi này sẽ luôn có sẵn cho bạn.

Chức năng: Phạm vi địa phương

Phạm vi hoặc phạm vi hàm cục bộ là phạm vi Python được tạo tại các cuộc gọi chức năng. Mỗi khi bạn gọi một chức năng, bạn cũng sẽ tạo ra một phạm vi địa phương mới. Mặt khác, bạn có thể nghĩ về từng tuyên bố

>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
3 và biểu thức
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
1 như một kế hoạch chi tiết cho phạm vi địa phương mới. Những phạm vi địa phương này sẽ ra đời bất cứ khi nào bạn gọi chức năng trong tay.local scope or function scope is a Python scope created at function calls. Every time you call a function, you’re also creating a new local scope. On the other hand, you can think of each
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
3 statement and
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
1 expression as a blueprint for new local scopes. These local scopes will come into existence whenever you call the function at hand.

Theo mặc định, các tham số và tên mà bạn gán bên trong một hàm chỉ tồn tại trong hàm hoặc phạm vi cục bộ được liên kết với lệnh gọi hàm. Khi hàm trở lại, phạm vi cục bộ bị phá hủy và tên bị lãng quên. Ở đây, cách thức hoạt động của nó:

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 là một hàm tính toán bình phương của một số đã cho,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 (một đối số) và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 (một biến cục bộ). Sau cuộc gọi đầu tiên đến
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
0 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ giá trị là
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2. Lần thứ hai, các tên địa phương sẽ không nhớ các giá trị được lưu trữ trong chúng lần đầu tiên hàm được gọi. Lưu ý rằng
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 hiện giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
4 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
6.

Vì bạn có thể truy cập tên cục bộ từ các câu lệnh nằm ngoài hàm, các chức năng khác nhau có thể xác định các đối tượng có cùng tên. Kiểm tra ví dụ này:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 là một hàm tính toán bình phương của một số đã cho,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 (một đối số) và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 (một biến cục bộ). Sau cuộc gọi đầu tiên đến
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
0 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ giá trị là
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2. Lần thứ hai, các tên địa phương sẽ không nhớ các giá trị được lưu trữ trong chúng lần đầu tiên hàm được gọi. Lưu ý rằng
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 hiện giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
4 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
6.

Vì bạn có thể truy cập tên cục bộ từ các câu lệnh nằm ngoài hàm, các chức năng khác nhau có thể xác định các đối tượng có cùng tên. Kiểm tra ví dụ này:

Lưu ý rằng bạn xác định

>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
7 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4. Tuy nhiên, vì
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
7 có thể thấy các tên bên trong phạm vi địa phương của
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 và ngược lại, cả hai chức năng đều hoạt động như mong đợi mà không có bất kỳ sự va chạm tên nào.

>>>

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 là một hàm tính toán bình phương của một số đã cho,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 (một đối số) và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 (một biến cục bộ). Sau cuộc gọi đầu tiên đến
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
0 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ giá trị là
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2. Lần thứ hai, các tên địa phương sẽ không nhớ các giá trị được lưu trữ trong chúng lần đầu tiên hàm được gọi. Lưu ý rằng
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 hiện giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
4 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
6.

Vì bạn có thể truy cập tên cục bộ từ các câu lệnh nằm ngoài hàm, các chức năng khác nhau có thể xác định các đối tượng có cùng tên. Kiểm tra ví dụ này:

Lưu ý rằng bạn xác định

>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
7 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4. Tuy nhiên, vì
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
7 có thể thấy các tên bên trong phạm vi địa phương của
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 và ngược lại, cả hai chức năng đều hoạt động như mong đợi mà không có bất kỳ sự va chạm tên nào.
is observed when you nest functions inside other functions. The enclosing scope was added in Python 2.2. It takes the form of the local scope of any enclosing function’s local scopes. Names that you define in the enclosing Python scope are commonly known as nonlocal names. Consider the following code:

>>>

>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 là một hàm tính toán bình phương của một số đã cho,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 (một đối số) và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 (một biến cục bộ). Sau cuộc gọi đầu tiên đến
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
0 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ giá trị là
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2. Lần thứ hai, các tên địa phương sẽ không nhớ các giá trị được lưu trữ trong chúng lần đầu tiên hàm được gọi. Lưu ý rằng
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 hiện giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
4 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
6.enclosing scope.

Vì bạn có thể truy cập tên cục bộ từ các câu lệnh nằm ngoài hàm, các chức năng khác nhau có thể xác định các đối tượng có cùng tên. Kiểm tra ví dụ này:

>>>

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 là một hàm tính toán bình phương của một số đã cho,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 (một đối số) và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 (một biến cục bộ). Sau cuộc gọi đầu tiên đến
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4,
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
0 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ giá trị là
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2. Lần thứ hai, các tên địa phương sẽ không nhớ các giá trị được lưu trữ trong chúng lần đầu tiên hàm được gọi. Lưu ý rằng
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
5 hiện giữ giá trị
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
4 và
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
7 giữ
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
6.

Vì bạn có thể truy cập tên cục bộ từ các câu lệnh nằm ngoài hàm, các chức năng khác nhau có thể xác định các đối tượng có cùng tên. Kiểm tra ví dụ này:

Lưu ý rằng bạn xác định >>> var = 100 >>> def func(): ... return var # You can access var from inside func() ... >>> func() 100 >>> var # Remains unchanged 100 7 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong >>> dir() ['__annotations__', '__builtins__',..., '__package__', '__spec__'] >>> var = 100 # Assign var at the top level of __main__ >>> dir() ['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var'] 4. Tuy nhiên, vì >>> var = 100 >>> def func(): ... return var # You can access var from inside func() ... >>> func() 100 >>> var # Remains unchanged 100 7 có thể thấy các tên bên trong phạm vi địa phương của >>> dir() ['__annotations__', '__builtins__',..., '__package__', '__spec__'] >>> var = 100 # Assign var at the top level of __main__ >>> dir() ['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var'] 4 và ngược lại, cả hai chức năng đều hoạt động như mong đợi mà không có bất kỳ sự va chạm tên nào.

Bạn có thể tránh va chạm tên trong các chương trình của mình bằng cách sử dụng đúng phạm vi Python cục bộ. Điều này cũng làm cho các chức năng khép kín hơn và tạo ra các đơn vị chương trình có thể duy trì. Ngoài ra, vì bạn có thể thay đổi tên địa phương từ các địa điểm từ xa trong mã của bạn, các chương trình của bạn sẽ dễ dàng gỡ lỗi, đọc và sửa đổi hơn.global scope of your program.

Bạn có thể kiểm tra các tên và tham số của một hàm bằng cách sử dụng

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
01, đây là một thuộc tính chứa thông tin về mã nội bộ của hàm. Hãy xem mã bên dưới:

>>>

>>> __name__
'__main__'

Bất cứ khi nào bạn chạy chương trình Python hoặc phiên tương tác như trong mã trên, trình thông dịch sẽ thực thi mã trong mô -đun hoặc tập lệnh đóng vai trò là điểm nhập cho chương trình của bạn. Mô -đun hoặc tập lệnh này được tải với tên đặc biệt,

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
21. Từ thời điểm này, bạn có thể nói rằng phạm vi toàn cầu chính của bạn là phạm vi của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
21.

Để kiểm tra các tên trong phạm vi toàn cầu chính của bạn, bạn có thể sử dụng

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25. Nếu bạn gọi
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25 mà không có đối số, thì bạn sẽ nhận được danh sách các tên sống trong phạm vi toàn cầu hiện tại của bạn. Hãy xem mã này:

>>>

>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100  # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']

Khi bạn gọi

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25 không có đối số, bạn sẽ nhận được danh sách các tên có sẵn trong phạm vi Python toàn cầu chính của bạn. Lưu ý rằng nếu bạn gán một tên mới (như
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 ở đây) ở cấp cao nhất của mô -đun (là
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
21 tại đây), thì tên đó sẽ được thêm vào danh sách được trả về bởi
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25.

Có một phạm vi Python toàn cầu trên mỗi lần thực hiện chương trình. Phạm vi này vẫn tồn tại cho đến khi chương trình chấm dứt và tất cả các tên của nó bị lãng quên. Mặt khác, lần sau khi bạn chạy chương trình, các tên sẽ nhớ các giá trị của chúng từ lần chạy trước đó.

Bạn có thể truy cập hoặc tham khảo giá trị của bất kỳ tên toàn cầu nào từ bất kỳ nơi nào trong mã của bạn. Điều này bao gồm các chức năng và các lớp học. Ở đây, một ví dụ làm rõ những điểm này:

>>>

>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100

Bên trong

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
31, bạn có thể tự do truy cập hoặc tham chiếu giá trị của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28. Điều này không ảnh hưởng đến tên toàn cầu của bạn
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28, nhưng nó cho bạn thấy rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 có thể được truy cập tự do từ trong vòng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
31. Mặt khác, bạn có thể gán tên toàn cầu bên trong các chức năng trừ khi bạn tuyên bố rõ ràng chúng là tên toàn cầu bằng cách sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 mà bạn sẽ thấy sau này.

Bất cứ khi nào bạn gán một giá trị cho một tên trong Python, một trong hai điều có thể xảy ra:

  1. Bạn tạo một tên mớicreate a new name
  2. Bạn cập nhật một tên hiện cóupdate an existing name

Hành vi cụ thể sẽ phụ thuộc vào phạm vi Python trong đó bạn đang gán tên. Nếu bạn cố gắng gán một giá trị cho một tên toàn cầu bên trong một hàm, thì bạn sẽ tạo ra tên đó trong phạm vi địa phương chức năng, bóng tối hoặc ghi đè tên toàn cầu. Điều này có nghĩa là bạn đã thắng được có thể thay đổi hầu hết các biến đã được xác định bên ngoài hàm từ bên trong hàm.

Nếu bạn tuân theo logic này, thì bạn sẽ nhận ra rằng mã sau đây đã giành được công việc như bạn mong đợi:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0

Trong

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37, bạn cố gắng tăng biến toàn cầu,
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28. Vì
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 được khai báo
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 bên trong
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37, Python tạo ra một biến cục bộ mới có cùng tên,
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28, bên trong hàm. Trong quá trình này, Python nhận ra rằng bạn đang cố gắng sử dụng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 cục bộ trước khi được chuyển nhượng đầu tiên (
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
44), do đó, nó tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45.

Ở đây, một ví dụ khác:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
1

Bạn có thể mong đợi có thể in toàn cầu

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 và có thể cập nhật
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 sau, nhưng một lần nữa bạn nhận được
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45. Điều xảy ra ở đây là khi bạn chạy phần thân của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
31, Python quyết định rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 là một biến cục bộ vì nó được gán trong phạm vi hàm. Đây là một lỗi, nhưng là một lựa chọn thiết kế. Python giả định rằng các tên được gán trong phần thân của một hàm là cục bộ cho chức năng đó.

Cho đến thời điểm này, bạn đã bao gồm ba phạm vi Python. Kiểm tra ví dụ sau đây để tóm tắt về nơi họ đặt trong mã của bạn và cách Python tìm kiếm tên thông qua chúng:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
2

Khi bạn gọi

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
06, bạn sẽ được in trên màn hình. Nhưng làm thế nào để Python tra cứu tên
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
53 trong trường hợp này? Theo quy tắc LegB, bạn sẽ tìm kiếm
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
53 ở những nơi sau:

  1. Bên trong
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    08: Đây là phạm vi địa phương, nhưng
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 không tồn tại ở đó.
    This is the local scope, but
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 doesn’t exist there.
  2. Bên trong
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    06: Đây là phạm vi bao quanh, nhưng
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 cũng được xác định ở đó.
    This is the enclosing scope, but
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 isn’t defined there either.
  3. Trong phạm vi mô -đun: Đây là phạm vi toàn cầu và bạn tìm thấy
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 ở đó, vì vậy bạn có thể in
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 lên màn hình.
    This is the global scope, and you find
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 there, so you can print
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    53 to the screen.

Nếu

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
53 được định nghĩa bên trong phạm vi toàn cầu, thì Python tiếp tục tìm kiếm bằng cách nhìn vào phạm vi tích hợp. Đây là thành phần cuối cùng của quy tắc LegB, như bạn sẽ thấy trong phần tiếp theo.

>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> ' 62: Phạm vi tích hợp

Phạm vi tích hợp là một phạm vi Python đặc biệt mà Lừa được triển khai như một mô-đun thư viện tiêu chuẩn có tên

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 trong Python 3.x. Tất cả các đối tượng tích hợp Python, sống trong mô-đun này. Họ tự động tải vào phạm vi tích hợp khi bạn chạy trình thông dịch Python. Python tìm kiếm
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 cuối cùng trong tra cứu LegB của nó, vì vậy bạn nhận được tất cả các tên mà nó xác định miễn phí. Điều này có nghĩa là bạn có thể sử dụng chúng mà không cần nhập bất kỳ mô -đun nào.built-in scope is a special Python scope that’s implemented as a standard library module named
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 in Python 3.x. All of Python’s built-in objects live in this module. They’re automatically loaded to the built-in scope when you run the Python interpreter. Python searches
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 last in its LEGB lookup, so you get all the names it defines for free. This means that you can use them without importing any module.

Lưu ý rằng các tên trong

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 luôn được tải vào phạm vi Python toàn cầu của bạn với tên đặc biệt
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66, như bạn có thể thấy trong mã sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
3

Trong đầu ra của cuộc gọi đầu tiên đến

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, bạn có thể thấy rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 bằng cách sử dụng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, thì bạn sẽ nhận được toàn bộ danh sách các tên tích hợp Python.

Phạm vi tích hợp mang lại hơn 150 tên cho phạm vi Python toàn cầu hiện tại của bạn. Ví dụ: trong Python 3.8, bạn có thể biết chính xác số lượng tên như sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
4

Trong đầu ra của cuộc gọi đầu tiên đến

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, bạn có thể thấy rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 bằng cách sử dụng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, thì bạn sẽ nhận được toàn bộ danh sách các tên tích hợp Python.

Phạm vi tích hợp mang lại hơn 150 tên cho phạm vi Python toàn cầu hiện tại của bạn. Ví dụ: trong Python 3.8, bạn có thể biết chính xác số lượng tên như sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
5

Trong đầu ra của cuộc gọi đầu tiên đến

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, bạn có thể thấy rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 bằng cách sử dụng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, thì bạn sẽ nhận được toàn bộ danh sách các tên tích hợp Python.

Phạm vi tích hợp mang lại hơn 150 tên cho phạm vi Python toàn cầu hiện tại của bạn. Ví dụ: trong Python 3.8, bạn có thể biết chính xác số lượng tên như sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
6

Trong đầu ra của cuộc gọi đầu tiên đến

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, bạn có thể thấy rằng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
66 bằng cách sử dụng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25, thì bạn sẽ nhận được toàn bộ danh sách các tên tích hợp Python.

Phạm vi tích hợp mang lại hơn 150 tên cho phạm vi Python toàn cầu hiện tại của bạn. Ví dụ: trong Python 3.8, bạn có thể biết chính xác số lượng tên như sau:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
7

Với cuộc gọi đến

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
71, bạn sẽ nhận được số lượng các mục trong
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
72 được trả về bởi
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
25. Điều này trả về 152 tên bao gồm các ngoại lệ, chức năng, loại, thuộc tính đặc biệt và các đối tượng tích hợp Python khác.

Mặc dù bạn có thể truy cập tất cả các đối tượng tích hợp Python này miễn phí (mà không cần nhập bất cứ thứ gì), bạn cũng có thể nhập rõ ràng

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 và truy cập tên bằng ký hiệu DOT. Ở đây, cách thức hoạt động của nó:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
8

Bạn có thể nhập

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 như bất kỳ mô -đun Python nào khác. Từ thời điểm này, bạn có thể truy cập tất cả các tên trong
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 bằng cách sử dụng Tra cứu thuộc tính chấm hoặc tên đủ điều kiện đầy đủ. Điều này có thể khá hữu ích nếu bạn muốn đảm bảo rằng bạn đã giành được một vụ va chạm tên nếu bất kỳ tên toàn cầu nào của bạn ghi đè bất kỳ tên tích hợp nào.

Bạn có thể ghi đè hoặc xác định lại bất kỳ tên tích hợp nào trong phạm vi toàn cầu của bạn. Nếu bạn làm như vậy, thì hãy nhớ rằng điều này sẽ ảnh hưởng đến tất cả các mã của bạn. Hãy xem ví dụ sau:

Nếu bạn ghi đè hoặc tham gia lại
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
77, thì
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
78 được tích hợp gốc sẽ bị ảnh hưởng trên tất cả các mã của bạn. Bây giờ, giả sử rằng bạn cần gọi là
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
78 gốc và bạn quên rằng bạn đã gán lại tên. Trong trường hợp này, khi bạn gọi
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
78 một lần nữa, bạn sẽ nhận được một
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
81 vì
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
77 hiện giữ một tham chiếu đến một số nguyên, không thể gọi được.
Nếu bạn đang thử nghiệm một số mã và bạn vô tình chỉ định lại tên tích hợp tại dấu nhắc tương tác, thì bạn có thể khởi động lại phiên của mình hoặc chạy
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
83 để xóa xác định lại khỏi phạm vi Python toàn cầu của bạn. Bằng cách này, bạn đã khôi phục tên ban đầu trong phạm vi tích hợp. Nếu bạn xem lại ví dụ của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
78, thì bạn có thể làm điều gì đó như sau:
Khi bạn xóa tên
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
77 tùy chỉnh, bạn sẽ xóa tên khỏi phạm vi toàn cầu của mình. Điều này cho phép bạn truy cập lại
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
78 ban đầu trong phạm vi tích hợp một lần nữa.
Để làm việc xung quanh loại tình huống này, bạn có thể nhập rõ ràng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62 và sau đó sử dụng các tên đủ điều kiện đầy đủ, như trong đoạn mã sau:
Khi bạn nhập rõ ràng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62, bạn có sẵn tên mô -đun trong phạm vi Python toàn cầu của bạn. Từ thời điểm này, bạn có thể sử dụng các tên đủ điều kiện để có được các tên bạn cần một cách rõ ràng từ
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
62, giống như bạn đã làm với
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
90 trong ví dụ trên.
Như một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:Như một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:Như một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:
Hoạt độngNhư một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:Hoạt độngHoạt động
Mã toàn cầuMã địa phươngMã chức năng lồng nhauMã chức năng lồng nhau
Tên truy cập hoặc tham chiếu sống trong phạm vi toàn cầuNhư một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:Hoạt độngHoạt động
Mã toàn cầuMã địa phươngMã địa phươngNhư một bản tóm tắt nhanh chóng, một số ý nghĩa của phạm vi Python được hiển thị trong bảng sau:
Hoạt độngMã địa phươngMã địa phươngMã chức năng lồng nhau

Tên truy cập hoặc tham chiếu sống trong phạm vi toàn cầu

Đúng

Sửa đổi hoặc cập nhật các tên sống trong phạm vi toàn cầuglobal names from any place in your code, but they can be modified or updated from within the global Python scope.

Không (trừ khi được tuyên bố

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6)local names only from inside the local Python scope they were created in or from inside a nested function, but you can’t access them from the global Python scope or from other local scopes. Additionally, you’ve learned that nonlocal names can be accessed from inside nested functions, but they can’t be modified or updated from there.

Mặc dù phạm vi Python tuân theo các quy tắc chung này theo mặc định, có nhiều cách để sửa đổi hành vi tiêu chuẩn này. Python cung cấp hai từ khóa cho phép bạn sửa đổi nội dung của các tên toàn cầu và không thuộc địa. Hai từ khóa này là:

  1. >>> square.__code__.co_varnames
    ('base', 'result')
    >>> square.__code__.co_argcount
    1
    >>> square.__code__.co_consts
    (None, 2, 'The square of ', ' is: ')
    >>> square.__code__.co_name
    'square'
    
    6
  2. >>> def outer_func():
    ...     # This block is the Local scope of outer_func()
    ...     var = 100  # A nonlocal var
    ...     # It's also the enclosing scope of inner_func()
    ...     def inner_func():
    ...         # This block is the Local scope of inner_func()
    ...         print(f"Printing var from inner_func(): {var}")
    ...
    ...     inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Printing var from outer_func(): 100
    >>> inner_func()
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'inner_func' is not defined
    
    2

Trong hai phần tiếp theo, bạn sẽ đề cập đến cách sử dụng các từ khóa Python này để sửa đổi hành vi tiêu chuẩn của phạm vi Python.

Tuyên bố >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 6

Bạn đã biết rằng khi bạn cố gắng gán một giá trị cho một tên toàn cầu bên trong hàm, bạn tạo một tên cục bộ mới trong phạm vi chức năng. Để sửa đổi hành vi này, bạn có thể sử dụng câu lệnh

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6. Với tuyên bố này, bạn có thể xác định một danh sách các tên sẽ được coi là tên toàn cầu.
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 statement
. With this statement, you can define a list of names that are going to be treated as global names.

Tuyên bố bao gồm từ khóa

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 theo sau là một hoặc nhiều tên được phân tách bằng dấu phẩy. Bạn cũng có thể sử dụng nhiều câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 có tên (hoặc danh sách tên). Tất cả các tên mà bạn liệt kê trong một câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 sẽ được ánh xạ vào phạm vi toàn cầu hoặc mô -đun mà bạn xác định chúng.

Dưới đây, một ví dụ mà bạn cố gắng cập nhật một biến toàn cầu từ trong một hàm:

>>>

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
9

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
0

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:

Trong phiên bản mới này của

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, bạn thêm câu lệnh
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
10 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 trong phạm vi hàm thành cùng tên trong phạm vi toàn cầu hoặc mô -đun. Từ thời điểm này, bạn có thể tự do sửa đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
1

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:

Trong phiên bản mới này của

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, bạn thêm câu lệnh
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
10 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 trong phạm vi hàm thành cùng tên trong phạm vi toàn cầu hoặc mô -đun. Từ thời điểm này, bạn có thể tự do sửa đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
2

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 6 như sau:

Trong phiên bản mới này của

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, bạn thêm câu lệnh
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
10 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 trong phạm vi hàm thành cùng tên trong phạm vi toàn cầu hoặc mô -đun. Từ thời điểm này, bạn có thể tự do sửa đổi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
2 statement
. With a
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
2 statement, you can define a list of names that are going to be treated as nonlocal.

Với tuyên bố

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
10, bạn đã nói với Python để xem xét phạm vi toàn cầu cho tên
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03. Bằng cách này, biểu thức
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
17 không tạo ra một tên mới trong phạm vi hàm, nhưng cập nhật nó trong phạm vi toàn cầu.

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
3

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
4

Khi bạn cố gắng gán

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 bên trong
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04, Python giả định rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
03 là cục bộ của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
04 và tăng
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
45 vì bạn đã cố gắng truy cập một cái tên được xác định.

Trái ngược với

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6, bạn có thể sử dụng
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
2 để tạo ra tên không đáng lười biếng. Tên phải tồn tại trong phạm vi Python kèm theo nếu bạn muốn sử dụng chúng dưới dạng tên không thuộc địa. Điều này có nghĩa là bạn có thể tạo ra các tên không thuộc địa điểm bằng cách khai báo chúng trong một tuyên bố
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
2 trong một hàm lồng nhau. Hãy xem ví dụ mã sau:

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
5

Trong ví dụ này, khi bạn cố gắng xác định tên không thuộc địa bằng cách sử dụng

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
54, Python ngay lập tức tăng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
48 vì
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
56 không tồn tại trong phạm vi kèm theo của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
39.

Sử dụng phạm vi kèm theo làm việc đóng cửa

Đóng cửa là một trường hợp sử dụng đặc biệt của phạm vi Python kèm theo. Khi bạn xử lý một hàm lồng nhau làm dữ liệu, các câu lệnh tạo thành hàm đó được đóng gói cùng với môi trường mà chúng thực thi. Đối tượng kết quả được gọi là đóng cửa. Nói cách khác, việc đóng là một chức năng bên trong hoặc lồng nhau mang thông tin về phạm vi bao quanh của nó, mặc dù phạm vi này đã hoàn thành việc thực thi. are a special use case of the enclosing Python scope. When you handle a nested function as data, the statements that make up that function are packaged together with the environment in which they execute. The resulting object is known as a closure. In other words, a closure is an inner or nested function that carries information about its enclosing scope, even though this scope has completed its execution.

Đóng cửa cung cấp một cách để giữ lại thông tin trạng thái giữa các cuộc gọi chức năng. Điều này có thể hữu ích khi bạn muốn viết mã dựa trên khái niệm đánh giá lười biếng hoặc bị trì hoãn. Hãy xem mã sau đây để biết ví dụ về cách đóng cửa hoạt động và cách bạn có thể tận dụng chúng trong Python:

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
6

Trong ví dụ này, khi bạn cố gắng xác định tên không thuộc địa bằng cách sử dụng

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
54, Python ngay lập tức tăng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
48 vì
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
56 không tồn tại trong phạm vi kèm theo của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
39.

Sử dụng phạm vi kèm theo làm việc đóng cửa

Đóng cửa là một trường hợp sử dụng đặc biệt của phạm vi Python kèm theo. Khi bạn xử lý một hàm lồng nhau làm dữ liệu, các câu lệnh tạo thành hàm đó được đóng gói cùng với môi trường mà chúng thực thi. Đối tượng kết quả được gọi là đóng cửa. Nói cách khác, việc đóng là một chức năng bên trong hoặc lồng nhau mang thông tin về phạm vi bao quanh của nó, mặc dù phạm vi này đã hoàn thành việc thực thi.

>>>

Trong ví dụ này, khi bạn cố gắng xác định tên không thuộc địa bằng cách sử dụng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
54, Python ngay lập tức tăng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
48 vì
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
56 không tồn tại trong phạm vi kèm theo của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
39.

Sử dụng phạm vi kèm theo làm việc đóng cửa

Đóng cửa là một trường hợp sử dụng đặc biệt của phạm vi Python kèm theo. Khi bạn xử lý một hàm lồng nhau làm dữ liệu, các câu lệnh tạo thành hàm đó được đóng gói cùng với môi trường mà chúng thực thi. Đối tượng kết quả được gọi là đóng cửa. Nói cách khác, việc đóng là một chức năng bên trong hoặc lồng nhau mang thông tin về phạm vi bao quanh của nó, mặc dù phạm vi này đã hoàn thành việc thực thi.

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
8

Đóng cửa cung cấp một cách để giữ lại thông tin trạng thái giữa các cuộc gọi chức năng. Điều này có thể hữu ích khi bạn muốn viết mã dựa trên khái niệm đánh giá lười biếng hoặc bị trì hoãn. Hãy xem mã sau đây để biết ví dụ về cách đóng cửa hoạt động và cách bạn có thể tận dụng chúng trong Python:

Hàm nhà máy đóng cửa của bạn

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
58 có một đối số gọi là
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59. Bạn có thể sử dụng chức năng này để xây dựng các đóng cửa chạy các hoạt động năng lượng khác nhau. Điều này hoạt động vì mỗi cuộc gọi đến
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
58 có được bộ thông tin trạng thái riêng. Nói cách khác, nó nhận được giá trị của nó cho
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59.

>>>

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
9

Trong ví dụ trên, hàm bên trong

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
62 trước tiên được gán cho
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
63. Trong trường hợp này, chức năng nhớ rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59 bằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
65. Trong ví dụ thứ hai, bạn gọi
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
58 bằng cách sử dụng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
67 làm đối số. Bằng cách này,
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
68 giữ một đối tượng hàm, nhớ rằng
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59 là
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
67. Lưu ý rằng bạn có thể tự do sử dụng lại
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
63 và
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
68 vì họ không quên thông tin trạng thái tương ứng của họ.

Để biết ví dụ cuối cùng về cách sử dụng đóng cửa, giả sử rằng bạn cần tính giá trị trung bình của một số dữ liệu mẫu. Bạn thu thập dữ liệu thông qua một luồng các phép đo liên tiếp của tham số mà bạn đang phân tích. Trong trường hợp này, bạn có thể sử dụng một nhà máy đóng cửa để tạo ra một đóng cửa để nhớ các phép đo trước đó trong mẫu. Hãy xem mã sau:

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
7

Việc đóng cửa mà bạn tạo trong mã trên nhớ thông tin trạng thái của

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
73 giữa các cuộc gọi của
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
74. Bằng cách này, bạn có thể giải quyết vấn đề một cách thanh lịch và pythonic.

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
0

Lưu ý rằng nếu luồng dữ liệu của bạn quá lớn, thì chức năng này có thể trở thành một vấn đề về việc sử dụng bộ nhớ. Điều đó bởi vì với mỗi cuộc gọi đến

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
74,
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
73 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng
>>> def outer_func():
...     # This block is the Local scope of outer_func()
...     var = 100  # A nonlocal var
...     # It's also the enclosing scope of inner_func()
...     def inner_func():
...         # This block is the Local scope of inner_func()
...         print(f"Printing var from inner_func(): {var}")
...
...     inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'inner_func' is not defined
2:

Trong hoạt động

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
84 mới nhất, bạn sử dụng biểu mẫu
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
93. Bằng cách này, bạn có thể sử dụng tên đã nhập trực tiếp trong mã của mình. Nói cách khác, bạn không cần phải sử dụng rõ ràng ký hiệu dấu chấm.

Khám phá phạm vi Python bất thường

Bạn sẽ tìm thấy một số cấu trúc python nơi độ phân giải tên dường như không phù hợp với quy tắc LegB cho phạm vi Python. Các cấu trúc này bao gồm:

  • Sự hiểu biết
  • Khối ngoại lệ
  • Các lớp học và trường hợp

Trong một vài phần tiếp theo, bạn sẽ đề cập đến cách Python Phạm vi hoạt động trên ba cấu trúc này. Với kiến ​​thức này, bạn sẽ có thể tránh các lỗi tinh tế liên quan đến việc sử dụng tên trong các loại cấu trúc python này.

Phạm vi biến hiểu

Cấu trúc đầu tiên mà bạn bao gồm là sự hiểu biết. Sự hiểu biết là một cách nhỏ gọn để xử lý tất cả hoặc một phần của các yếu tố trong một bộ sưu tập hoặc trình tự. Bạn có thể sử dụng toàn bộ để tạo danh sách, từ điển và bộ.comprehension. A comprehension is a compact way to process all or part of the elements in a collection or sequence. You can use comprehensions to create lists, dictionaries, and sets.

Các hệ thống bao gồm một cặp dấu ngoặc (

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
94) hoặc niềng răng xoăn (
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
95) chứa một biểu thức, tiếp theo là một hoặc nhiều điều khoản ____296 và sau đó không hoặc một mệnh đề
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
97 trên mệnh đề
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96.

Điều khoản

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 trong một sự hiểu biết hoạt động tương tự như vòng lặp
>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 truyền thống. Biến vòng lặp trong một khả năng hiểu là cục bộ với cấu trúc. Kiểm tra mã sau:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
1

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
2

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp >>> def square(base): ... result = base ** 2 ... print(f'The square of {base} is: {result}') ... >>> square(10) The square of 10 is: 100 >>> result # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in result NameError: name 'result' is not defined >>> base # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in base NameError: name 'base' is not defined >>> square(20) The square of 20 is: 400 96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:

Bạn có thể tự do truy cập biến vòng lặp

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 sau khi vòng lặp kết thúc. Ở đây, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp, đó là
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
04 trong ví dụ này.exception variable. The exception variable is a variable that holds a reference to the exception raised by a
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
05 statement. In Python 3.x, such variables are local to the
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
06 block and are forgotten when the block ends. Check out the following code:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
3

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
4

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp >>> def square(base): ... result = base ** 2 ... print(f'The square of {base} is: {result}') ... >>> square(10) The square of 10 is: 100 >>> result # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in result NameError: name 'result' is not defined >>> base # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in base NameError: name 'base' is not defined >>> square(20) The square of 20 is: 400 96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:

Bạn có thể tự do truy cập biến vòng lặp

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 sau khi vòng lặp kết thúc. Ở đây, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp, đó là
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
04 trong ví dụ này.L level.

Phạm vi biến ngoại lệclass attributes live. Check out this code:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
5

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp

>>> def square(base):
...     result = base ** 2
...     print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    result
NameError: name 'result' is not defined
>>> base  # Isn't accessible from outside square()
Traceback (most recent call last):
  File "", line 1, in 
    base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
6

Khi bạn chạy danh sách hiểu, biến

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
01 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.

Mặt khác, nếu bạn cố gắng truy cập một thuộc tính được xác định bên trong một lớp, thì bạn sẽ nhận được một

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31. Kiểm tra ví dụ sau:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
7

Trong ví dụ này, bạn cố gắng truy cập thuộc tính

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32. Vì thuộc tính này không tồn tại trong
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26, bạn nhận được một
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 nói với bạn rằng
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26 không có thuộc tính có tên
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32.

Bạn cũng có thể truy cập bất kỳ thuộc tính nào bằng cách sử dụng một thể hiện của lớp như sau:

>>>

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
8

Trong ví dụ này, bạn cố gắng truy cập thuộc tính

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32. Vì thuộc tính này không tồn tại trong
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26, bạn nhận được một
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 nói với bạn rằng
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26 không có thuộc tính có tên
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32.

Bạn cũng có thể truy cập bất kỳ thuộc tính nào bằng cách sử dụng một thể hiện của lớp như sau:instance attributes and are local and specific to each instance. This means that if you modify an instance attribute, then the changes will be visible only to that specific instance.

Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
37. Các thuộc tính lớp dành riêng cho đối tượng lớp, nhưng bạn có thể truy cập chúng từ bất kỳ trường hợp nào của lớp. Nó đáng chú ý rằng các thuộc tính lớp là phổ biến cho tất cả các trường hợp của một lớp. Nếu bạn sửa đổi thuộc tính lớp, thì các thay đổi sẽ được hiển thị trong tất cả các trường hợp của lớp.

>>>

Trong ví dụ này, bạn cố gắng truy cập thuộc tính
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32. Vì thuộc tính này không tồn tại trong
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26, bạn nhận được một
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 nói với bạn rằng
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26 không có thuộc tính có tên
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
32.

Bạn cũng có thể truy cập bất kỳ thuộc tính nào bằng cách sử dụng một thể hiện của lớp như sau:

Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
37. Các thuộc tính lớp dành riêng cho đối tượng lớp, nhưng bạn có thể truy cập chúng từ bất kỳ trường hợp nào của lớp. Nó đáng chú ý rằng các thuộc tính lớp là phổ biến cho tất cả các trường hợp của một lớp. Nếu bạn sửa đổi thuộc tính lớp, thì các thay đổi sẽ được hiển thị trong tất cả các trường hợp của lớp.

>>>

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
0

Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính

>>> def outer_func():
...     var = 100
...     def inner_func():
...         print(f"Printing var from inner_func(): {var}")
...         print(f"Printing another_var from inner_func(): {another_var}")
...
...     inner_func()
...     another_var = 200  # This is defined after calling inner_func()
...     print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
  File "", line 1, in 
    outer_func()
  File "", line 7, in outer_func
    inner_func()
  File "", line 5, in inner_func
    print(f"Printing another_var from inner_func(): {another_var}")
NameError: free variable 'another_var' referenced before assignment in enclosing
 scope
1 của riêng họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó.

Để tạo, cập nhật hoặc truy cập bất kỳ thuộc tính nào từ bên trong lớp, bạn cần sử dụng

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
39 cùng với ký hiệu chấm. Ở đây,
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
39 là một thuộc tính đặc biệt đại diện cho thể hiện hiện tại. Mặt khác, để cập nhật hoặc truy cập bất kỳ thuộc tính nào từ bên ngoài lớp, bạn cần tạo một thể hiện và sau đó sử dụng ký hiệu dấu chấm. Ở đây, cách thức hoạt động của nó:

  1. >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    9instance local scope or namespace first.
  2. Lớp
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    26 có một đối số gọi là
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    28, được tự động tăng gấp đôi bên trong
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    43 bằng cách sử dụng thao tác gán
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    44. Lưu ý rằng khi bạn kiểm tra
    >>> def outer_func():
    ...     var = 100
    ...     def inner_func():
    ...         print(f"Printing var from inner_func(): {var}")
    ...         print(f"Printing another_var from inner_func(): {another_var}")
    ...
    ...     inner_func()
    ...     another_var = 200  # This is defined after calling inner_func()
    ...     print(f"Printing var from outer_func(): {var}")
    ...
    >>> outer_func()
    Printing var from inner_func(): 100
    Traceback (most recent call last):
      File "", line 1, in 
        outer_func()
      File "", line 7, in outer_func
        inner_func()
      File "", line 5, in inner_func
        print(f"Printing another_var from inner_func(): {another_var}")
    NameError: free variable 'another_var' referenced before assignment in enclosing
     scope
    
    1 trên
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    46, bạn sẽ nhận được một từ điển chứa tất cả các thuộc tính thể hiện. Trong trường hợp này, từ điển chỉ chứa tên
    >>> sys.ps1
    '>>> '
    >>> sys.__dict__['ps1']
    '>>> '
    
    28, có giá trị hiện là
    >>> def square(base):
    ...     result = base ** 2
    ...     print(f'The square of {base} is: {result}')
    ...
    >>> square(10)
    The square of 10 is: 100
    >>> result  # Isn't accessible from outside square()
    Traceback (most recent call last):
      File "", line 1, in 
        result
    NameError: name 'result' is not defined
    >>> base  # Isn't accessible from outside square()
    Traceback (most recent call last):
      File "", line 1, in 
        base
    NameError: name 'base' is not defined
    >>> square(20)
    The square of 20 is: 400
    
    42.class local scope or namespace.
  3. Mặc dù bạn có thể tạo các thuộc tính thể hiện trong bất kỳ phương thức nào trong một lớp, nhưng nó thực hành tốt để tạo và khởi tạo chúng bên trong
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    43. Hãy xem phiên bản mới này của
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    26:
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    31
    .

Tại đây, bạn sửa đổi

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26 để thêm một phương thức mới gọi là
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
52. Sau đó, bạn tạo một thể hiện là
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
26 bằng cách chuyển trong
>>> var = 100
>>> def func():
...     return var  # You can access var from inside func()
...
>>> func()
100
>>> var  # Remains unchanged
100
2 cho trình khởi tạo lớp. Sau đó, bây giờ bạn có thể gọi
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
52 trên
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
46 để nhân đôi giá trị được lưu trữ trong
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
57. Cuối cùng, nếu bạn cố gắng truy cập
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 bằng cách sử dụng đối tượng lớp thay vì một thể hiện, thì bạn sẽ nhận được
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 vì các thuộc tính thể hiện có thể được truy cập bằng cách sử dụng các đối tượng lớp.

Nói chung, khi bạn viết mã hướng đối tượng bằng Python và bạn cố gắng truy cập một thuộc tính, chương trình của bạn thực hiện các bước sau:

>>>

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
1

Kiểm tra phạm vi địa phương hoặc không gian tên trước.

Nếu thuộc tính không được tìm thấy ở đó, thì hãy kiểm tra phạm vi hoặc không gian tên cục bộ của lớp.

>>>

>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
2

Nếu tên không tồn tại trong không gian tên lớp, thì bạn sẽ nhận được

>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31.

  1. Đây là cơ chế cơ bản mà Python giải quyết các tên trong các lớp học và trường hợp. Use
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    57 to access this attribute.
  2. Mặc dù các lớp xác định phạm vi hoặc không gian tên cục bộ lớp, nhưng chúng không tạo ra phạm vi kèm theo các phương thức. Do đó, khi bạn thực hiện một lớp, các tham chiếu đến các thuộc tính và phương thức phải được thực hiện bằng cách sử dụng ký hiệu chấm: Use
    >>> def cube(base):
    ...     result = base ** 3
    ...     print(f'The cube of {base} is: {result}')
    ...
    >>> cube(30)
    The cube of 30 is: 27000
    
    68 to access this attribute.

Vì các lớp don lồng tạo ra một phạm vi kèm theo cho các phương thức, bạn có thể truy cập

>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
28 trực tiếp từ trong vòng
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
62 như bạn cố gắng làm ở đây. Để có quyền truy cập vào các thuộc tính lớp từ bên trong bất kỳ phương thức nào, bạn cần sử dụng ký hiệu dấu chấm. Để khắc phục sự cố trong ví dụ này, hãy thay đổi câu lệnh
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
63 bên trong
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
62 thành
>>> def cube(base):
...     result = base ** 3
...     print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
65 và xem điều gì sẽ xảy ra.

Bạn có thể ghi đè thuộc tính lớp với thuộc tính thể hiện, sẽ sửa đổi hành vi chung của lớp của bạn. Tuy nhiên, bạn có thể truy cập cả hai thuộc tính rõ ràng bằng cách sử dụng ký hiệu dấu chấm như trong ví dụ sau:

Sự kết luận

Phạm vi của một biến hoặc tên xác định khả năng hiển thị của nó trong suốt mã của bạn. Trong Python, phạm vi được thực hiện dưới dạng phạm vi địa phương, bao quanh, toàn cầu hoặc tích hợp. Khi bạn sử dụng một biến hoặc tên, Python tìm kiếm các phạm vi này một cách tuần tự để giải quyết nó. Nếu tên được tìm thấy, thì bạn sẽ gặp lỗi. Đây là cơ chế chung mà Python sử dụng để giải quyết tên và được gọi là Quy tắc LEGB.scope of a variable or name defines its visibility throughout your code. In Python, scope is implemented as either a Local, Enclosing, Global, or Built-in scope. When you use a variable or name, Python searches these scopes sequentially to resolve it. If the name isn’t found, then you’ll get an error. This is the general mechanism that Python uses for name resolution and is known as the LEGB rule.

Bây giờ bạn có thể:

  • Tận dụng phạm vi Python để tránh hoặc giảm thiểu các lỗi liên quan đến va chạm tên advantage of Python scope to avoid or minimize bugs related to name collision
  • Sử dụng tốt các tên toàn cầu và địa phương trên các chương trình của bạn để cải thiện khả năng duy trì mã good use of global and local names across your programs to improve code maintainability
  • Sử dụng chiến lược kết hợp để truy cập, sửa đổi hoặc cập nhật tên trên tất cả mã Python của bạn a coherent strategy to access, modify, or update names across all your Python code

Ngoài ra, bạn đã đề cập đến một số công cụ và kỹ thuật liên quan đến phạm vi mà Python cung cấp và cách bạn có thể sử dụng chúng để thu thập thông tin về các tên sống trong một phạm vi nhất định hoặc để sửa đổi hành vi tiêu chuẩn của phạm vi Python. Tất nhiên, có nhiều hơn nữa về chủ đề này mà bên ngoài phạm vi của hướng dẫn này, vì vậy hãy ra khỏi đó và tiếp tục giải quyết độ phân giải tên trong Python!

Phạm vi của một đối tượng là gì?

Một đối tượng có thể nhìn thấy trong một tập tin khối hoặc nguồn nếu kiểu dữ liệu của nó và tên được khai báo được biết đến trong tệp khối hoặc tệp.Vùng nơi có thể nhìn thấy một đối tượng được gọi là phạm vi của nó.The region where an object is visible is referred to as its scope.

Các loại phạm vi trong Python là gì?

Bạn sẽ tìm hiểu về bốn phạm vi khác nhau với sự trợ giúp của các ví dụ: địa phương, bao quanh, toàn cầu và tích hợp.Các phạm vi này cùng nhau tạo thành cơ sở cho quy tắc LEGB được sử dụng bởi trình thông dịch Python khi làm việc với các biến.local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.

Quy tắc phạm vi trong Python là gì?

Quy tắc LEGB đặt tên cho các phạm vi có thể có của một biến trong Python: Local, bao quanh, toàn cầu, tích hợp.Python tìm kiếm các không gian tên theo thứ tự này để xác định giá trị của một đối tượng được đặt tên.Phạm vi được tạo ra với các chức năng, lớp và mô -đun.

Phạm vi của các biến trong Python là gì?

Một biến chỉ có sẵn từ bên trong khu vực nó được tạo ra.Đây được gọi là phạm vi.. This is called scope.