Trong trường hợp đầu tiên, bạn đang đề cập đến một biến
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0 là OK vì không có biến cục bộ gọi là class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
1.def toplevel[]:
a = 5
def nested[]:
print[a + 2] # theres no local variable a so it prints the nonlocal one
nested[]
return a
Trong trường hợp thứ hai, bạn tạo một biến cục bộ
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
1 cũng tốt [cục bộ class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
1 sẽ khác với loại không phải là lý do tại sao class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
1 ban đầu không thay đổi].def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
Trong trường hợp thứ ba, bạn tạo một biến cục bộ nhưng bạn có
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
5 trước đó và đó là lý do tại sao ngoại lệ được nâng lên. Bởi vì class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
5 sẽ đề cập đến biến cục bộ class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
1 được tạo sau dòng đó.def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
Để đạt được những gì bạn muốn, bạn cần sử dụng
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
8 bên trong chức năng bên trong của bạn:def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
Tôi có mã sau:
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
Tuy nhiên,
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
9 lỗi với new_str
new_str
new_str
new_str
new_str
0Làm thế nào tôi có thể tham gia lại biến
new_str
new_str
new_str
new_str
new_str
1 trong lớp mới?Hỏi ngày 22 tháng 8 lúc 23:56Aug 22 at 23:56
Có 2 vấn đề với điều này. Đầu tiên là bạn cần xác định
new_str
new_str
new_str
new_str
new_str
2 và new_str
new_str
new_str
new_str
new_str
1 là thành viên của new_str
new_str
new_str
new_str
new_str
4, không phải là new_str
new_str
new_str
new_str
new_str
5 trong một phương thức. Bạn sẽ không thể truy cập chúng theo cách đó. Thứ hai là bạn cần một ví dụ là new_str
new_str
new_str
new_str
new_str
4 trong new_str
new_str
new_str
new_str
new_str
7:class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
Output:
new_str
new_str
new_str
new_str
new_str
Đã trả lời ngày 23 tháng 8 lúc 0:35Aug 23 at 0:35
dmedinedmedinedmedine
1.1169 huy hiệu bạc23 Huy hiệu đồng9 silver badges23 bronze badges
0
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
8 vànew_str new_str new_str new_str new_str
0standard behavior of Python scope usingclass MyFirstClass: x = 'some_str' y = 0 class MySecondClass: myFirstClass = MyFirstClass[] def myOtherDef[self]: for i in range[10]: self.myFirstClass.y += 1 if self.myFirstClass.y % 2 == 0: self.myFirstClass.y = 0 self.myFirstClass.x = 'new_str' print[self.myFirstClass.x] mySecondClass = MySecondClass[] mySecondClass.myOtherDef[]
8 andnew_str new_str new_str new_str new_str
0class MyFirstClass: x = 'some_str' y = 0 class MySecondClass: myFirstClass = MyFirstClass[] def myOtherDef[self]: for i in range[10]: self.myFirstClass.y += 1 if self.myFirstClass.y % 2 == 0: self.myFirstClass.y = 0 self.myFirstClass.x = 'new_str' print[self.myFirstClass.x] mySecondClass = MySecondClass[] mySecondClass.myOtherDef[]
- 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:
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.
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
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
0 hoặc >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
1, 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:
Bài tập | 2 |
HOẠT ĐỘNG HOẠT ĐỘNG | 3 hoặc 4 |
Định nghĩa chức năng | 5 |
Định nghĩa đối số trong bối cảnh của các chức năng | 6 |
Định nghĩa lớp | 7 |
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à
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8.namespaces. These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8.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 ____ ____78. Hãy xem mã sau:
>>>
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
Sau khi bạn nhập
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0, bạn có thể sử dụng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
1 để kiểm tra các khóa của >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
2. Đ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 >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 giữ không gian tên của >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0 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
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
5, được định nghĩa trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0. Nếu bạn biết cách >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
5 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
9>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
- Sử dụng hoạt động đăng ký trên
8 dưới dạng>>> import sys >>> sys.__dict__.keys[] dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
1>>> 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
Hãy xem mã sau:
>>>
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
Sau khi bạn nhập
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0, bạn có thể sử dụng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
1 để kiểm tra các khóa của >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
2. Đ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 >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 giữ không gian tên của >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0 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
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
5, được định nghĩa trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
0. Nếu bạn biết cách >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
5 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 >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
9
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
Sử dụng hoạt động đăng ký trên
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 dưới 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
1LEGB 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
8 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.>>> 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
Khi bạn đã nhập
0, bạn có thể truy cập>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
5 bằng cách sử dụng ký hiệu dấu chấm trên>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
0. Bạn cũng có thể truy cập>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
5 bằng cách sử dụng tra cứu khóa từ điển với khóa>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
6. Cả hai hành động trả về cùng một kết quả,>>> 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. 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.>>> 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
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
>>> 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. 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ố
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
0 và 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
8 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 >>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
0 statement and >>> 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 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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 là một hàm tính toán bình phương của một số đã cho, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 [một đối số] và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 [một biến cục bộ]. Sau cuộc gọi đầu tiên đến def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
07 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ giá trị là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 hiện giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
11 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
13.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 toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
0def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 là một hàm tính toán bình phương của một số đã cho, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 [một đối số] và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 [một biến cục bộ]. Sau cuộc gọi đầu tiên đến def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
07 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ giá trị là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 hiện giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
11 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
13.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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
14 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01. Tuy nhiên, vì def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
14 có thể thấy các tên bên trong phạm vi địa phương của def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 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.>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
1def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 là một hàm tính toán bình phương của một số đã cho, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 [một đối số] và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 [một biến cục bộ]. Sau cuộc gọi đầu tiên đến def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
07 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ giá trị là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 hiện giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
11 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
13.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
14 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01. Tuy nhiên, vì def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
14 có thể thấy các tên bên trong phạm vi địa phương của def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 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 toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
2def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 là một hàm tính toán bình phương của một số đã cho, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 [một đối số] và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 [một biến cục bộ]. Sau cuộc gọi đầu tiên đến def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
07 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ giá trị là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 hiện giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
11 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
13.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 toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
3def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 là một hàm tính toán bình phương của một số đã cho, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 [một đối số] và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 [một biến cục bộ]. Sau cuộc gọi đầu tiên đến def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
07 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ giá trị là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
02 hiện giữ giá trị def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
11 và def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
04 giữ def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
13.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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
14 bằng cách sử dụng cùng một biến và tham số mà bạn đã sử dụng trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01. Tuy nhiên, vì def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
14 có thể thấy các tên bên trong phạm vi địa phương của def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
01 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.
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
18, đâ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:>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
4Bấ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,
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
38. 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
38.Để 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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42. Nếu bạn gọi def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42 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:>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
5Khi bạn gọi
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42 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ư def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 ở đây] ở cấp cao nhất của mô -đun [là def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
38 tại đây], thì tên đó sẽ được thêm vào danh sách được trả về bởi def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42.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:
>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
6Bên trong
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
48, bạn có thể tự do truy cập hoặc tham chiếu giá trị của def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45. Điều này không ảnh hưởng đến tên toàn cầu của bạn def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45, nhưng nó cho bạn thấy rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 có thể được truy cập tự do từ trong vòng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
48. 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 new_str
new_str
new_str
new_str
new_str
8 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:
- Bạn tạo một tên mớicreate a new name
- 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:
>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
7Trong
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
54, bạn cố gắng tăng biến toàn cầu, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45. Vì def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 được khai báo new_str
new_str
new_str
new_str
new_str
8 bên trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
54, Python tạo ra một biến cục bộ mới có cùng tên, def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45, 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 cục bộ trước khi phân công đầu tiên [def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
61], do đó, nó tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62.Ở đây, một ví dụ khác:
>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
8Bạn có thể mong đợi có thể in toàn cầu
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 và có thể cập nhật def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 sau, nhưng một lần nữa bạn nhận được def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62. Điều xảy ra ở đây là khi bạn chạy phần thân của def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
48, Python quyết định rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 là một biến cục bộ vì nó được gán trong phạm vi chức năng. Đâ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:
>>>
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
9Khi bạn gọi
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
23, bạn sẽ được in trên màn hình của mình. Nhưng làm thế nào để Python tra cứu tên def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
70 trong trường hợp này? Theo quy tắc LegB, bạn sẽ tìm kiếm def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
70 ở những nơi sau:- Bên trong
25: Đây là phạm vi địa phương, nhưngdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 không tồn tại ở đó. This is the local scope, butdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 doesn’t exist there.def toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
- Bên trong
23: Đây là phạm vi bao quanh, nhưngdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 cũng không được xác định ở đó. This is the enclosing scope, butdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 isn’t defined there either.def toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
- Trong phạm vi mô -đun: Đây là phạm vi toàn cầu và bạn tìm thấy
70 ở đó, vì vậy bạn có thể indef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 lên màn hình. This is the global scope, and you finddef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 there, so you can printdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
70 to the screen.def toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
Nếu
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
70 đượ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.def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79: Phạm vi tích hợp
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83, như bạn có thể thấy trong mã sau:>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
0Trong đầu ra của cuộc gọi đầu tiên đến
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, bạn có thể thấy rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 bằng cách sử dụng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, 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:
>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
1Trong đầu ra của cuộc gọi đầu tiên đến
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, bạn có thể thấy rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 bằng cách sử dụng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, 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:
>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
2Trong đầu ra của cuộc gọi đầu tiên đến
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, bạn có thể thấy rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 bằng cách sử dụng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, 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:
>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
3Trong đầu ra của cuộc gọi đầu tiên đến
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, bạn có thể thấy rằng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 luôn có mặt trong phạm vi Python toàn cầu. Nếu bạn kiểm tra def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
83 bằng cách sử dụng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42, 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:
>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
4Với cuộc gọi đến
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
88, bạn sẽ nhận được số lượng các mục trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
89 được trả về bởi def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
42. Đ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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 và truy cập tên bằng ký hiệu DOT. Ở đây, cách thức hoạt động của nó:>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
5Bạn có thể nhập
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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 def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
79 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:
Khi bạn nhập rõ ràng 79, 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ừ 79, giống như bạn đã làm với 07 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 động | 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 động | Hoạt động |
Mã toàn cầu | Mã địa phương | Mã chức năng lồng nhau | Mã 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 | 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 động | Hoạt động |
Mã toàn cầu | Mã địa phương | Mã địa phương | 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 động | Mã địa phương | Mã địa phương | Mã 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ố
new_str
new_str
new_str
new_str
new_str
8]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à:
8new_str new_str new_str new_str new_str
0class MyFirstClass: x = 'some_str' y = 0 class MySecondClass: myFirstClass = MyFirstClass[] def myOtherDef[self]: for i in range[10]: self.myFirstClass.y += 1 if self.myFirstClass.y % 2 == 0: self.myFirstClass.y = 0 self.myFirstClass.x = 'new_str' print[self.myFirstClass.x] mySecondClass = MySecondClass[] mySecondClass.myOtherDef[]
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ố new_str
new_str
new_str
new_str
new_str
8
new_str
new_str
new_str
new_str
new_str
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
new_str
new_str
new_str
new_str
new_str
8. 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.new_str
new_str
new_str
new_str
new_str
8 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
new_str
new_str
new_str
new_str
new_str
8 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 new_str
new_str
new_str
new_str
new_str
8 với 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 new_str
new_str
new_str
new_str
new_str
8 sẽ được ánh xạ vào phạm vi toàn cầu hoặc mô -đun trong đó 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:
>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
6Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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
new_str
new_str
new_str
new_str
new_str
8 như sau:>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
7Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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
new_str
new_str
new_str
new_str
new_str
8 như sau:Trong phiên bản mới này của
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, bạn thêm câu lệnh def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
27 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
8Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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
new_str
new_str
new_str
new_str
new_str
8 như sau:Trong phiên bản mới này của
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, bạn thêm câu lệnh def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
27 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>>
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
9Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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 new_str
new_str
new_str
new_str
new_str
8 như sau:
new_str
new_str
new_str
new_str
new_str
Trong phiên bản mới này của
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, bạn thêm câu lệnh def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
27 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0 statement. With a class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0 statement, you can define a list of names that are going to be treated as nonlocal.Với tuyên bố
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
27, bạn có thể nói với Python để xem xét phạm vi toàn cầu cho tên def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20. Bằng cách này, biểu thức def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
34 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
0Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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
new_str
new_str
new_str
new_str
new_str
8 như sau:>>>
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
1Khi bạn cố gắng gán
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 bên trong def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21, Python giả định rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
20 là cục bộ của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
21 và tăng def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
62 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
new_str
new_str
new_str
new_str
new_str
8, bạn có thể sử dụng class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0 để tạo ra những cái tên không đáng sợ. 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ố class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0 trong một hàm lồng nhau. Hãy xem ví dụ mã sau:>>>
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
2Trong 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
71, Python ngay lập tức tăng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
65 vì def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
73 không tồn tại trong phạm vi kèm theo của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
56.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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
3Trong 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
71, Python ngay lập tức tăng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
65 vì def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
73 không tồn tại trong phạm vi kèm theo của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
56.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ụngdef toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
71, Python ngay lập tức tăng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
65 vì def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
73 không tồn tại trong phạm vi kèm theo của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
56.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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
5Đó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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
75 có một đối số gọi là def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
76. 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
75 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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
76.>>>
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
6Trong ví dụ trên, hàm bên trong
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
79 trước tiên được gán cho def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
80. Trong trường hợp này, chức năng nhớ rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
76 bằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
82. Trong ví dụ thứ hai, bạn gọi def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
75 bằng cách sử dụng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
84 làm đối số. Bằng cách này, def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
85 giữ một đối tượng hàm, nhớ rằng def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
76 là def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
84. Lưu ý rằng bạn có thể tự do sử dụng lại def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
80 và def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
85 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
4Việc đóng cửa mà bạn tạo trong mã trên nhớ thông tin trạng thái của
def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
90 giữa các cuộc gọi của def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
91. 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
7Lư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 toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
91, def toplevel[]:
a = 5
def nested[]:
print[a + 2] # tries to print local variable a but its created after this line so exception is raised
a = 7
nested[]
return a
toplevel[]
90 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 class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass[]
def myOtherDef[self]:
for i in range[10]:
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print[self.myFirstClass.x]
mySecondClass = MySecondClass[]
mySecondClass.myOtherDef[]
0:Trong hoạt động
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
01 mới nhất, bạn sử dụng biểu mẫu def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
10. 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.
Sự hiểu biết bao gồm một cặp dấu ngoặc [
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
11] hoặc niềng răng xoăn [def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
12] chứa một biểu thức, tiếp theo là một hoặc nhiều điều khoản def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 và sau đó không hoặc một mệnh đề def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
14 trên mệnh đề def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13.Điều khoản
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 trong một sự hiểu biết hoạt động tương tự như vòng lặp def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
8Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
9Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
Bạn có thể tự do truy cập biến vòng lặp
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
21 trong ví dụ này.exception variable. The exception variable is a variable that holds a reference to the exception raised by a
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
22 statement. In Python 3.x, such variables are local to the def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
23 block and are forgotten when the block ends. Check out the following code:>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
0Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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:>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
1Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
Bạn có thể tự do truy cập biến vòng lặp
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
21 trong ví dụ này.L level.
Phạm vi biến ngoại lệclass attributes live. Check out this code:
>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
2Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
13 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:>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
3Khi bạn chạy danh sách hiểu, biến
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
18 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48. Kiểm tra ví dụ sau:>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
4Trong ví dụ này, bạn cố gắng truy cập thuộc tính
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49. Vì thuộc tính này không tồn tại trong def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43, bạn nhận được một def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48 nói với bạn rằng def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43 không có thuộc tính có tên def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49.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:
>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
5Trong ví dụ này, bạn cố gắng truy cập thuộc tính
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49. Vì thuộc tính này không tồn tại trong def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43, bạn nhận được một def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48 nói với bạn rằng def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43 không có thuộc tính có tên def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49.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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
54. 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ínhdef toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49. Vì thuộc tính này không tồn tại trong def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43, bạn nhận được một def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48 nói với bạn rằng def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43 không có thuộc tính có tên def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
49.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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
54. 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.>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
7Bấ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
>>> import sys
>>> sys.__dict__.keys[]
dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
8 riêng của chúng chứa 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
56 cùng với ký hiệu chấm. Ở đây, def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
56 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ó:
6instance local scope or namespace first.class MyFirstClass: def myDef[self]: global x, y x = 'some_str' y = 0 class MySecondClass: def myOtherDef[self]: for i in range[10]: y += 1 if y % 2 == 0: y = 0 x = 'new_str'
- Lớp
43 có một đối số gọi làdef toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
45, được tự động tăng gấp đôi bên trongdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
60 bằng cách sử dụng thao tác gándef toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
61. Lưu ý rằng khi bạn kiểm tradef toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
8 trên>>> import sys >>> sys.__dict__.keys[] dict_keys[['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']]
63, 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êndef toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
45, có giá trị hiện làdef toplevel[]: a = 5 def nested[]: a = 7 # create a local variable called a which is different than the nonlocal one print[a] # prints 7 nested[] print[a] # prints 5 return a
59.class local scope or namespace.def toplevel[]: a = 5 def nested[]: print[a + 2] # tries to print local variable a but its created after this line so exception is raised a = 7 nested[] return a toplevel[]
- 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
60. Hãy xem phiên bản mới này củadef toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
43:def toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
48.def toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
Tại đây, bạn sửa đổi
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43 để thêm một phương thức mới gọi là def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
69. Sau đó, bạn tạo một thể hiện là def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
43 bằng cách chuyển trong def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
09 cho trình khởi tạo lớp. Sau đó, bây giờ bạn có thể gọi def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
69 trên def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
63 để nhân đôi giá trị được lưu trữ trong def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
74. Cuối cùng, nếu bạn cố gắng truy cập def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48 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:
>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
8Kiể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.
>>>
class MyFirstClass:
def myDef[self]:
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef[self]:
for i in range[10]:
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
9Nếu tên không tồn tại trong không gian tên lớp, thì bạn sẽ nhận được một
def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
48.- Đâ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
74 to access this attribute.def toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
- 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
85 to access this attribute.def toplevel[]: a = 5 def nested[]: nonlocal a print[a + 2] a = 7 nested[] return a
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
def toplevel[]:
a = 5
def nested[]:
a = 7 # create a local variable called a which is different than the nonlocal one
print[a] # prints 7
nested[]
print[a] # prints 5
return a
45 trực tiếp từ trong vòng ____379 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 toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
80 bên trong def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
79 thành def toplevel[]:
a = 5
def nested[]:
nonlocal a
print[a + 2]
a = 7
nested[]
return a
82 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!