Hướng dẫn what is scope resolving rule in python - quy tắc giải quyết phạm vi trong python là gì
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. Show
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:
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 viTrong 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 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 PythonVì 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 5 hoặc 6, 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:
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ênTrong 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à 3.namespaces. These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called 3.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ọ đã được lưu trữ trong thuộc tính mô -đun ____ ____53. Hãy xem mã sau: >>>
Sau khi bạn nhập 5, bạn có thể sử dụng 6 để kiểm tra các khóa của 7. Đ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 3 giữ không gian tên của 5 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 0, được định nghĩa trong 5. Nếu bạn biết cách 3 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo 0 theo ít nhất hai cách khác nhau:
Hãy xem mã sau: >>>
Sau khi bạn nhập 5, bạn có thể sử dụng 6 để kiểm tra các khóa của 7. Đ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 3 giữ không gian tên của 5 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 0, được định nghĩa trong 5. Nếu bạn biết cách 3 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo 0 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 >>> def outer_func():
... var = 100
... def inner_func():
... print(f"Printing var from inner_func(): {var}")
... print(f"Printing another_var from inner_func(): {another_var}")
...
... inner_func()
... another_var = 200 # This is defined after calling inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Traceback (most recent call last):
File " |
Hoạt động | Mã toàn cầu | 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 | Đúng | Đúng |
Sửa đổi hoặc cập nhật các tên 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ầu | Sửa đổi hoặc cập nhật các tên sống trong phạm vi toàn cầu |
Không (trừ khi được tuyên bố 3) | Các tên truy cập hoặc tham chiếu sống trong phạm vi địa phương | Không | Không |
Có (phạm vi địa phương của riêng nó), không (phạm vi địa phương khác) | Đúng | Sửa đổi hoặc cập nhật các tên sống trong phạm vi toàn cầu | Sửa đổi hoặc cập nhật các tên sống trong phạm vi toàn cầu |
Không (trừ khi được tuyên bố 3) | Các tên truy cập hoặc tham chiếu sống trong phạm vi địa phương | Các tên truy cập hoặc tham chiếu sống trong phạm vi địa phương | Đúng |
Sửa đổi hoặc cập nhật các tên sống trong phạm vi toàn cầu | Các tên truy cập hoặc tham chiếu sống trong phạm vi địa phương | Các tên truy cập hoặc tham chiếu sống trong phạm vi địa phương | Không |
Có (phạm vi địa phương của riêng nó), không (phạm vi địa phương khác)
Ghi đè tên trong phạm vi tích hợp
Có (trong quá trình thực thi chức năng)global names from any place in your code, but they can be modified or updated from within the global Python scope.
Các tên truy cập hoặc tham chiếu sống trong phạm vi bao quanh của họ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.
N/a
3>>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square'
4>>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square'
Sửa đổi hoặc cập nhật các tên sống trong phạm vi kèm theo của chúng
Không (trừ khi được tuyên bố >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 4)
Bạn đã biết rằng khi bạn cố gắng gán một giá trị cho một tên toàn cầu bên trong hàm, bạn tạo một tên cục bộ mới trong phạm vi chức năng. Để sửa đổi hành vi này, bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3. Với tuyên bố này, bạn có thể xác định một danh sách các tên sẽ được coi là tên toàn cầu.>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 statement. With this statement, you can
define a list of names that are going to be treated as global names.Tuyên bố bao gồm từ khóa
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 theo sau là một hoặc nhiều tên được phân tách bằng dấu phẩy. Bạn cũng có thể sử dụng nhiều câu lệnh >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 có tên (hoặc danh sách tên). Tất cả các tên mà bạn liệt kê trong một câu lệnh >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 sẽ được ánh xạ vào phạm vi toàn cầu hoặc mô -đun mà bạn xác định chúng.Dưới đây, một ví dụ mà bạn cố gắng cập nhật một biến toàn cầu từ trong một hàm:
>>>
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
9Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 như sau:>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
0Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 như sau:Trong phiên bản mới này của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, bạn thêm câu lệnh >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
02 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 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 >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
1Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 như sau:Trong phiên bản mới này của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, bạn thêm câu lệnh >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
02 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 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 >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
2Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 3 như sau:
Trong phiên bản mới này của
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, bạn thêm câu lệnh >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
02 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tên >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 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 >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
4 statement. With a >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
4 statement, you can define a list of names that are going to be treated as nonlocal.Với tuyên bố
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
02, bạn đã nói với Python để xem xét phạm vi toàn cầu cho tên >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95. Bằng cách này, biểu thức >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
09 không tạo ra một tên mới trong phạm vi hàm, nhưng cập nhật nó trong phạm vi toàn cầu.>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
3Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 như sau:>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
4Khi bạn cố gắng gán
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 bên trong >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96, Python giả định rằng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
95 là địa phương đến >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
96 và tăng >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
37 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
3 như sau:>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
5Trong ví dụ này, khi bạn cố gắng xác định tên không thuộc địa bằng cách sử dụng
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
46, Python ngay lập tức tăng >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
40 vì >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
48 không tồn tại trong phạm vi kèm theo của >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
31.Sử dụng phạm vi kèm theo làm việc đóng cửa
Đóng cửa là một trường hợp sử dụng đặc biệt của phạm vi Python kèm theo. Khi bạn xử lý một hàm lồng nhau làm dữ liệu, các câu lệnh tạo thành hàm đó được đóng gói cùng với môi trường mà chúng thực thi. Đối tượng kết quả được gọi là đóng cửa. Nói cách khác, việc đóng là một chức năng bên trong hoặc lồng nhau mang thông tin về phạm vi bao quanh của nó, mặc dù phạm vi này đã hoàn thành việc thực thi. are a special use case of the enclosing Python scope. When you handle a nested function as data, the statements that make up that function are packaged together with the environment in which they execute. The resulting object is known as a closure. In other words, a closure is an inner or nested function that carries information about its enclosing scope, even though this scope has completed its execution.
Đóng cửa cung cấp một cách để giữ lại thông tin trạng thái giữa các cuộc gọi chức năng. Điều này có thể hữu ích khi bạn muốn viết mã dựa trên khái niệm đánh giá lười biếng hoặc bị trì hoãn. Hãy xem mã sau đây để biết ví dụ về cách đóng cửa hoạt động và cách bạn có thể tận dụng chúng trong Python:
>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
6Hàm nhà máy đóng cửa của bạn
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
50 có một đối số gọi là >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
51. 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 bởi vì mỗi cuộc gọi đến >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
50 đều có bộ thông tin trạng thái riêng. Nói cách khác, nó nhận được giá trị của nó cho >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
51.Trong ví dụ trên, hàm bên trong
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
54 trước tiên được gán cho >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
55. Trong trường hợp này, chức năng nhớ rằng >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
51 bằng >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
57. Trong ví dụ thứ hai, bạn gọi >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
50 bằng cách sử dụng >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59 làm đối số. Bằng cách này, >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
60 giữ một đối tượng hàm, nhớ rằng >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
51 là >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
59. Lưu ý rằng bạn có thể tự do sử dụng lại >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
55 và >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
60 vì họ không quên thông tin trạng thái tương ứng của họ.Để biết ví dụ cuối cùng về cách sử dụng đóng cửa, giả sử rằng bạn cần tính giá trị trung bình của một số dữ liệu mẫu. Bạn thu thập dữ liệu thông qua một luồng các phép đo liên tiếp của tham số mà bạn đang phân tích. Trong trường hợp này, bạn có thể sử dụng một nhà máy đóng cửa để tạo ra một đóng cửa để nhớ các phép đo trước đó trong mẫu. Hãy xem mã sau:
>>>
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
7Việc đóng cửa mà bạn tạo trong mã trên nhớ thông tin trạng thái của
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
65 giữa các cuộc gọi của >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
66. 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.Lưu ý rằng nếu luồng dữ liệu của bạn quá lớn, thì chức năng này có thể trở thành một vấn đề về việc sử dụng bộ nhớ. Điều đó bởi vì với mỗi cuộc gọi đến
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
66, >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
65 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 >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
4:>>>
>>> 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
8Mặc dù giải pháp này là nhiều dòng hơn, bạn không có một danh sách phát triển vô tận nữa. Bây giờ bạn có một giá trị duy nhất cho
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
70 và >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
71. Việc triển khai này hiệu quả hơn rất nhiều về mức tiêu thụ bộ nhớ so với giải pháp trước đó.Cuối cùng, bạn có thể tìm thấy một số ví dụ về việc sử dụng đóng cửa trong thư viện tiêu chuẩn Python. Ví dụ,
>>> 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
72 cung cấp một chức năng có tên >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
73 sử dụng kỹ thuật đóng để tạo các đối tượng chức năng mới có thể được gọi bằng cách sử dụng các đối số được xác định trước. Đây là một ví dụ:>>>
>>> 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
9Bạn sử dụng
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
74 để xây dựng một đối tượng hàm nhớ thông tin trạng thái, trong đó >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
75. Sau đó, bạn gọi đối tượng này để thực hiện hoạt động năng lượng và nhận kết quả cuối cùng.Mang tên cho phạm vi với >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
76
Khi bạn viết một chương trình Python, bạn thường tổ chức mã thành một số mô -đun. Để chương trình của bạn hoạt động, bạn sẽ cần phải mang tên trong các mô -đun riêng biệt đó vào mô -đun
>>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
13 của bạn. Để làm điều đó, bạn cần phải >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
76 các mô -đun hoặc tên một cách rõ ràng. Đây là cách duy nhất bạn có thể sử dụng những tên đó trong phạm vi Python toàn cầu chính của bạn.Hãy xem mã sau đây để biết ví dụ về những gì xảy ra khi bạn nhập một số mô -đun và tên tiêu chuẩn:
>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
0Đầu tiên bạn nhập
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
5 và >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
80 từ Thư viện tiêu chuẩn Python. Bằng cách gọi >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
17 không có đối số, bạn có thể thấy rằng các mô -đun này hiện có sẵn cho bạn dưới dạng tên trong phạm vi toàn cầu hiện tại của bạn. Bằng cách này, bạn có thể sử dụng ký hiệu DOT để có quyền truy cập vào các tên được xác định trong >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
5 và >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
80.Trong hoạt động
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
76 mới nhất, bạn sử dụng biểu mẫu >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
85. 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 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
86) hoặc niềng răng xoăn (>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
87) chứa một biểu thức, tiếp theo là một hoặc nhiều điều khoản >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 và sau đó không hoặc một mệnh đề >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
89 trên mệnh đề >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88.Điều khoản
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 trong một sự hiểu biết hoạt động tương tự như vòng lặp >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 truyền thống. Biến vòng lặp trong một khả năng hiểu là cục bộ với cấu trúc. Kiểm tra mã sau:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
1Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
2Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:
Bạn có thể tự do truy cập biến vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
93 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 square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 trong ví dụ này.exception variable. The exception variable is a variable that holds a reference to the exception raised by a
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
97 statement. In Python 3.x, such variables are local to the >>> 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
98 block and are forgotten when the block ends. Check out the following code:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
3Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
4Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "", line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:
Bạn có thể tự do truy cập biến vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
93 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 square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
96 trong ví dụ này.L level.
Phạm vi biến ngoại lệclass attributes live. Check out this code:
>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
5Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
6Khi bạn chạy danh sách hiểu, biế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
93 bị lãng quên và bạn có thể truy cập giá trị của nó nữa. Nó không có khả năng bạn cần sử dụng biến này ngoài sự hiểu biết, nhưng bất kể, Python đảm bảo rằng giá trị của nó không còn khả dụng khi sự hiểu biết kết thúc.Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp
>>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
88 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
7Trong ví dụ này, bạn cố gắng truy cập thuộc tính
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
24. Vì thuộc tính này không tồn tại trong >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18, bạn nhận được một >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
23 nói với bạn rằng >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 không có thuộc tính có tên >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
24.Bạn cũng có thể truy cập bất kỳ thuộc tính nào bằng cách sử dụng một thể hiện của lớp như sau:
>>>
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
8Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
29. 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.Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
3 riêng của họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó.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.Để tạo, cập nhật hoặc truy cập bất kỳ thuộc tính nào từ bên trong lớp, bạn cần sử dụng
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 cùng với ký hiệu chấm. Ở đây, >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 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ó:>>>
Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
29. 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.Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
3 riêng của họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó.Để tạo, cập nhật hoặc truy cập bất kỳ thuộc tính nào từ bên trong lớp, bạn cần sử dụng
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 cùng với ký hiệu chấm. Ở đây, >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
31 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ó:>>>
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
0Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
29. 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.Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
3 riêng của họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó.- Để tạo, cập nhật hoặc truy cập bất kỳ thuộc tính nào từ bên trong lớp, bạn cần sử dụng
31 cùng với ký hiệu chấm. Ở đây,>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
31 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ó:instance local scope or namespace first.>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
9class local scope or namespace.>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
- Lớp
18 có một đối số gọi là>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
20, được tự động tăng gấp đôi bên trong>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
35 bằng cách sử dụng thao tác gán>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
36. Lưu ý rằng khi bạn kiểm tra>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
3 trên>>> def outer_func(): ... # This block is the Local scope of outer_func() ... var = 100 # A nonlocal var ... # It's also the enclosing scope of inner_func() ... def inner_func(): ... # This block is the Local scope of inner_func() ... print(f"Printing var from inner_func(): {var}") ... ... inner_func() ... print(f"Printing var from outer_func(): {var}") ... >>> outer_func() Printing var from inner_func(): 100 Printing var from outer_func(): 100 >>> inner_func() Traceback (most recent call last): File "
" , line 1, inNameError: name 'inner_func' is not defined
38, bạn sẽ nhận được một từ điển chứa tất cả các thuộc tính thể hiện. Trong trường hợp này, từ điển chỉ chứa tên>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
20, có giá trị hiện là>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> '
34.>>> 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, inresult NameError: name 'result' is not defined >>> base # Isn't accessible from outside square() Traceback (most recent call last): File " " , line 1, inbase NameError: name 'base' is not defined >>> square(20) The square of 20 is: 400
23.>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
Mặc dù bạn có thể tạo các thuộc tính thể hiện trong bất kỳ phương thức nào trong một lớp, nhưng nó thực hành tốt để tạo và khởi tạo chúng bên trong
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
35. Hãy xem phiên bản mới này của >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18:Tại đây, bạn sửa đổi
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 để thêm một phương thức mới gọi là >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
44. Sau đó, bạn tạo một thể hiện là >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 bằng cách chuyển trong >>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100 # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 cho trình khởi tạo lớp. Sau đó, bây giờ bạn có thể gọi >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
44 trên >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
38 để nhân đôi giá trị được lưu trữ trong >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
49. Cuối cùng, nếu bạn cố gắng truy cập >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
20 bằng cách sử dụng đối tượng lớp thay vì một thể hiện, thì bạn sẽ nhận được >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
23 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.>>>
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
1Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
29. 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.Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
3 riêng của họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó.>>>
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
2Khi bạn có thể hiện, bạn có thể truy cập các thuộc tính lớp bằng cách sử dụng ký hiệu dấu chấm, như bạn đã làm ở đây với
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
29. 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.- Bất cứ khi nào bạn gọi một lớp, bạn sẽ tạo một thể hiện mới của lớp đó. Các trường hợp có thuộc tính
3 riêng của họ giữ tên trong phạm vi địa phương hoặc không gian tên cục bộ. Các tên này thường được gọi là thuộc tính thể hiện và là cục bộ và cụ thể cho từng trường hợp. Điều này có nghĩa là nếu bạn sửa đổi một thuộc tính thể hiện, thì các thay đổi sẽ chỉ hiển thị cho trường hợp cụ thể đó. Use>>> def outer_func(): ... # This block is the Local scope of outer_func() ... var = 100 # A nonlocal var ... # It's also the enclosing scope of inner_func() ... def inner_func(): ... # This block is the Local scope of inner_func() ... print(f"Printing var from inner_func(): {var}") ... ... inner_func() ... print(f"Printing var from outer_func(): {var}") ... >>> outer_func() Printing var from inner_func(): 100 Printing var from outer_func(): 100 >>> inner_func() Traceback (most recent call last): File "
" , line 1, inNameError: name 'inner_func' is not defined
49 to access this attribute.>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
- Để 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
31 cùng với ký hiệu chấm. Ở đây,>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
31 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ó: Use>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
60 to access this attribute.>>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
9Lớp
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 có một đối số gọi là >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
20, được tự động tăng gấp đôi bên trong >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
35 bằng cách sử dụng thao tác gán >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
36. Lưu ý rằng khi bạn kiểm tra >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
3 trên >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
38, bạn sẽ nhận được một từ điển chứa tất cả các thuộc tính thể hiện. Trong trường hợp này, từ điển chỉ chứa tên >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
20, có giá trị hiện là >>> def square(base):
... result = base ** 2
... print(f'The square of {base} is: {result}')
...
>>> square(10)
The square of 10 is: 100
>>> result # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
result
NameError: name 'result' is not defined
>>> base # Isn't accessible from outside square()
Traceback (most recent call last):
File "" , line 1, in
base
NameError: name 'base' is not defined
>>> square(20)
The square of 20 is: 400
34.Mặc dù bạn có thể tạo các thuộc tính thể hiện trong bất kỳ phương thức nào trong một lớp, nhưng nó thực hành tốt để tạo và khởi tạo chúng bên trong >>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000 35. Hãy xem phiên bản mới này của >>> def cube(base): ... result = base ** 3 ... print(f'The cube of {base} is: {result}') ... >>> cube(30) The cube of 30 is: 27000 18:
Tại đây, bạn sửa đổi
>>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 để thêm một phương thức mới gọi là >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
44. Sau đó, bạn tạo một thể hiện là >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
18 bằng cách chuyển trong >>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__']
>>> var = 100 # Assign var at the top level of __main__
>>> dir()
['__annotations__', '__builtins__',..., '__package__', '__spec__', 'var']
4 cho trình khởi tạo lớp. Sau đó, bây giờ bạn có thể gọi >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
44 trên >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
38 để nhân đôi giá trị được lưu trữ trong >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
49. Cuối cùng, nếu bạn cố gắng truy cập >>> sys.ps1
'>>> '
>>> sys.__dict__['ps1']
'>>> '
20 bằng cách sử dụng đối tượng lớp thay vì một thể hiện, thì bạn sẽ nhận được >>> def cube(base):
... result = base ** 3
... print(f'The cube of {base} is: {result}')
...
>>> cube(30)
The cube of 30 is: 27000
23 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.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!