Hướng dẫn python object scope - phạm vi đối tượng python
Một biến chỉ có sẵn từ bên trong khu vực nó được tạo ra. Đây được gọi là phạm vi.scope.scope. Show
Nội dung chính ShowShow
Phạm vi địa phươngMột biến được tạo bên trong một hàm thuộc phạm vi cục bộ của hàm đó và chỉ có thể được sử dụng bên trong hàm đó. Thí dụMột biến được tạo bên trong một hàm có sẵn bên trong chức năng đó: def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 print(x) myfunc() Hãy tự mình thử » Chức năng bên trong chức năngNhư đã giải thích trong ví dụ trên, biến 3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:Thí dụMột biến được tạo bên trong một hàm có sẵn bên trong chức năng đó: def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 print(x) myfunc() Hãy tự mình thử » Chức năng bên trong chức năngNhư đã giải thích trong ví dụ trên, biến 3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 def myinnerfunc(): print(x) myinnerfunc() Thí dụMột biến được tạo bên trong một hàm có sẵn bên trong chức năng đó: def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 print(x) Hãy tự mình thử » myfunc() print(x) Chức năng bên trong chức năng Như đã giải thích trong ví dụ trên, biếndef myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 def myinnerfunc(): print(x) myinnerfunc() Thí dụMột biến được tạo bên trong một hàm có sẵn bên trong chức năng đó: def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 print(x) Hãy tự mình thử » myfunc() print(x) Chức năng bên trong chức năng Như đã giải thích trong ví dụ trên, biếndef myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 def myinnerfunc(): print(x) myinnerfunc() Biến cục bộ có thể được truy cập từ một hàm trong hàm: Thí dụMột biến được tạo bên trong một hàm có sẵn bên trong chức năng đó: def myfunc (): & nbsp; x = 300 & nbsp; in (x) myfunc() Hãy tự mình thử » Chức năng bên trong chức năng Như đã giải thích trong ví dụ trên, biến 3 không có sẵn bên ngoài hàm, nhưng nó có sẵn cho bất kỳ chức năng nào bên trong hàm:Thí dụdef myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 def myinnerfunc(): print(x) myinnerfunc() def myfunc (): & nbsp; x = 300 & nbsp; in (x) x = 300 print(x) Hãy tự mình thử » myfunc() Hãy tự mình thử » Hãy tự mình thử » Chức năng bên trong chức năngscope 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. Như đã giải thích trong ví dụ trên, biến 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.
Hãy tự mình thử » x = 200 print(x) 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:scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on. A name will only be visible to and accessible by the code in its scope. Several programming languages take advantage of scope for avoiding name collisions and unpredictable behaviors. Most commonly, you’ll distinguish two general scopes:scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on. A name will only be visible to and accessible by the code in its scope. Several programming languages take advantage of scope for avoiding name collisions and unpredictable behaviors. Most commonly, you’ll distinguish two general scopes:
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.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.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.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 3 hoặc 4, tương ứng. Cuối cùng, các mô -đun tồn tại sau khi bạn nhập chúng. Tóm lại, bạn có thể tạo tên Python thông qua một trong các hoạt động sau:
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.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à 41.namespaces. These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called 41.namespaces.
These are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called 41.Tên ở cấp cao nhất của một mô -đun được lưu trữ trong không gian tên mô -đun. Nói cách khác, họ đã lưu trữ trong thuộc tính mô -đun ____ ____61. Hãy xem mã sau: >>> 7Sau khi bạn nhập 43, bạn có thể sử dụng 44 để kiểm tra các khóa của 45. Đ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 41 giữ không gian tên của 43 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 48, được định nghĩa trong 43. Nếu bạn biết cách 41 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo 48 theo ít nhất hai cách khác nhau:
Hãy xem mã sau: >>> 0Sau khi bạn nhập 43, bạn có thể sử dụng 44 để kiểm tra các khóa của 45. Đ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 41 giữ không gian tên của 43 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 48, được định nghĩa trong 43. Nếu bạn biết cách 41 và không gian tên hoạt động trong Python, thì bạn có thể tham khảo 48 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 >>> 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' 72Sử dụng hoạt động đăng ký trên 41 ở dạng 74Hãy xem mã sau:LEGB 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:
33, bạn có thể truy cập 48 bằng cách sử dụng ký hiệu dấu chấm trên 43. Bạn cũng có thể truy cập 48 bằng cách sử dụng tra cứu khóa từ điển với khóa 79. Cả hai hành động trả về cùng một kết quả, 20. 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.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 21 nào. Phạm vi Python này chứa các tên mà bạn xác định bên trong hàm. Những tên này sẽ chỉ hiển thị từ mã của hàm. Nó được tạo ra tại Call Function Call, không phải ở định nghĩa chức năng, do đó, bạn sẽ có nhiều phạm vi cục bộ khác nhau như các cuộc gọi chức năng. Điều này đúng ngay cả khi bạn gọi cùng một hàm nhiều lần hoặc đệ quy. Mỗi cuộc gọi sẽ dẫn đến một phạm vi địa phương mới được tạo ra.Tại bất kỳ thời điểm nào trong quá trình thực hiện, bạn sẽ có nhiều nhất bốn phạm vi Python hoạt động, tính toán, bao quanh, toàn cầu và tích hợp phụ thuộc vào nơi bạn đang ở trong mã. Mặt khác, bạn sẽ luôn có ít nhất hai phạm vi hoạt động, đó là phạm vi toàn cầu và tích hợp. Hai phạm vi này sẽ luôn có sẵn cho bạn. Chức năng: Phạm vi địa phươngPhạ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ố 3 và biểu thức 21 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 3 statement and 21 expression as a blueprint for new local scopes. These local scopes will come into existence whenever you call the function at hand.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 3 statement and 21 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ó: >>> 4 24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.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: >>> 4 24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.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: 8 24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.Lưu ý rằng bạn xác định >>> 4 24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.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:
24. Tuy nhiên, vì 17 có thể thấy các tên bên trong phạm vi địa phương của 24 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:>>>
24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.enclosing scope.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: >>> 4 24 là một hàm tính toán bình phương của một số đã cho, 25. Khi bạn gọi hàm, Python tạo ra một phạm vi cục bộ chứa tên 25 (một đối số) và 27 (một biến cục bộ). Sau cuộc gọi đầu tiên đến 24, 25 giữ giá trị 10 và 27 giữ giá trị là 12. 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 25 hiện giữ giá trị 14 và 27 giữ 16.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: >>> 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 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 " |
Nếu bạn ghi đè hoặc tham gia lại 077, thì 078 được tích hợp gốc sẽ bị ảnh hưởng trên tất cả các mã của bạn. Bây giờ, giả sử rằng bạn cần gọi là 078 gốc và bạn quên rằng bạn đã gán lại tên. Trong trường hợp này, khi bạn gọi 078 một lần nữa, bạn sẽ nhận được một 081 vì 077 hiện giữ một tham chiếu đến một số nguyên, không thể gọi được. | Nếu bạn đang thử nghiệm một số mã và bạn vô tình chỉ định lại tên tích hợp tại dấu nhắc tương tác, thì bạn có thể khởi động lại phiên của mình hoặc chạy 083 để xóa xác định lại khỏi phạm vi Python toàn cầu của bạn. Bằng cách này, bạn đã khôi phục tên ban đầu trong phạm vi tích hợp. Nếu bạn xem lại ví dụ của 078, thì bạn có thể làm điều gì đó như sau: | Khi bạn xóa tên 077 tùy chỉnh, bạn sẽ xóa tên khỏi phạm vi toàn cầu của mình. Điều này cho phép bạn truy cập lại 078 ban đầu trong phạm vi tích hợp một lần nữa. | Để làm việc xung quanh loại tình huống này, bạn có thể nhập rõ ràng 062 và sau đó sử dụng các tên đủ điều kiện đầy đủ, như trong đoạn mã sau: |
---|---|---|---|
Khi bạn nhập rõ ràng 062, 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ừ 062, giống như bạn đã làm với 090 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
Tên truy cập hoặc tham chiếu sống trong phạm vi toàn cầu
Đúngglobal names from any place in your code, but they can be modified or updated from within the global Python scope.
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ố 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à:
6>>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square'
2>>> 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
Trong hai phần tiếp theo, bạn sẽ đề cập đến cách sử dụng các từ khóa Python này để sửa đổi hành vi tiêu chuẩn của phạm vi Python.
Tuyên bố >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 6
Bạn đã biết rằng khi bạn cố gắng gán một giá trị cho một tên toàn cầu bên trong hàm, bạn tạo một tên cục bộ mới trong phạm vi chức năng. Để sửa đổi hành vi này, bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6. Với tuyên bố này, bạn có thể xác định một danh sách các tên sẽ được coi là tên toàn cầu.>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 statement. With this statement, you can define a list of names that are going to be treated as global names.>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 statement. With this statement, you can define a list of names
that are going to be treated as global names.Tuyên bố bao gồm từ khóa
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 theo sau là một hoặc nhiều tên được phân tách bằng dấu phẩy. Bạn cũng có thể sử dụng nhiều câu lệnh >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 có tên (hoặc danh sách tên). Tất cả các tên mà bạn liệt kê trong một câu lệnh >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 sẽ được ánh xạ vào phạm vi toàn cầu hoặc mô -đun mà bạn xác định chúng.Dưới đây, một ví dụ mà bạn cố gắng cập nhật một biến toàn cầu từ trong một hàm:
>>>
>>> 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'
09Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:>>>
>>> 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'
40Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:Trong phiên bản mới này của
>>> 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'
404, bạn thêm 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'
410 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
403. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tê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'
403 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 >>> 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'
403 bên trong >>> 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'
404. 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'
41Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:Trong phiên bản mới này của
>>> 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'
404, bạn thêm 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'
410 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
403. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tê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'
403 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 >>> 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'
403 bên trong >>> 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'
404. 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'
42Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 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
Trong phiên bản mới này củ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'
404, bạn thêm 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'
410 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
403. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tê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'
403 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 >>> 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'
403 bên trong >>> 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'
404. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 statement. With a >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 statement, you can define a list of names that are going to be treated as nonlocal.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh >>> square.__code__.co_varnames ('base', 'result') >>> square.__code__.co_argcount 1 >>> square.__code__.co_consts (None, 2, 'The square of ', ' is: ') >>> square.__code__.co_name 'square' 6 như sau:
>>> 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'
404, bạn thêm 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'
410 vào phần thân của chức năng ngay trước khi bạn cố gắng thay đổi >>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
403. Với sự thay đổi nhỏ bé này, bạn đã ánh xạ tê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'
403 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 >>> 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'
403 bên trong >>> 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'
404. Tất cả các thay đổi sẽ phản ánh trong biến toàn cầu.>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 statement. With a >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 statement, you can define a list of names that are going to be treated as nonlocal.>>>
>>> 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'
43Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Nếu bạn muốn mã này hoạt động theo cách bạn mong đợi ở đây, thì bạn có thể sử dụng câu lệnh
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6 như sau:>>>
>>> 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'
44Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Trái ngược với
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6, bạn có thể sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 để tạo ra tên không đáng lười biếng. Tên phải tồn tại trong phạm vi Python kèm theo nếu bạn muốn sử dụng chúng dưới dạng tên không thuộc địa. Điều này có nghĩa là bạn có thể tạo ra các tên không thuộc địa điểm bằng cách khai báo chúng trong một tuyên bố >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 trong một hàm lồng nhau. Hãy xem ví dụ mã sau:>>>
>>> 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'
45Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 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
6, bạn có thể 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'
2 để tạo ra tên không đáng lười biếng. Tên phải tồn tại trong phạm vi Python kèm theo nếu bạn muốn sử dụng chúng dưới dạng tên không thuộc địa. Điều này có nghĩa là bạn có thể tạo ra các tên không thuộc địa điểm bằng cách khai báo chúng trong một tuyên bố >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "
2 trong một hàm lồng nhau. Hãy xem ví dụ mã sau: 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.>>> 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 "
Trong ví dụ này, khi bạn cố gắng xác định tên không thuộc địa bằng cách sử dụng
>>>
>>> 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'
46Khi bạn cố gắng gá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'
403 bên trong >>> 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'
404, Python giả định rằ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'
403 là cục bộ củ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'
404 và tă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'
045 vì bạn đã cố gắng truy cập một cái tên được xác định.Trái ngược với
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6, bạn có thể sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 để tạo ra tên không đáng lười biếng. Tên phải tồn tại trong phạm vi Python kèm theo nếu bạn muốn sử dụng chúng dưới dạng tên không thuộc địa. Điều này có nghĩa là bạn có thể tạo ra các tên không thuộc địa điểm bằng cách khai báo chúng trong một tuyên bố >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 trong một hàm lồng nhau. Hãy xem ví dụ mã sau:>>>
Khi bạn cố gắng gánTrái ngược với
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
6, bạn có thể sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 để tạo ra tên không đáng lười biếng. Tên phải tồn tại trong phạm vi Python kèm theo nếu bạn muốn sử dụng chúng dưới dạng tên không thuộc địa. Điều này có nghĩa là bạn có thể tạo ra các tên không thuộc địa điểm bằng cách khai báo chúng trong một tuyên bố >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2 trong một hàm lồng nhau. Hãy xem ví dụ mã sau:>>>
>>> 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'
48Trong 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
>>> 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'
454, Python ngay lập tức tă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'
448 vì >>> 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'
456 không tồn tại trong phạm vi kèm theo củ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'
439.Sử dụng phạm vi kèm theo làm việc đóng cử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'
49Đó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.
>>> 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' 454, Python ngay lập tức tă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' 448 vì >>> 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 56 không tồn tại trong phạm vi kèm theo củ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' 439.
>>> 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'
47Việc đóng cửa mà bạn tạo trong mã trên nhớ thông tin trạng thái củ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'
473 giữa các cuộc gọi củ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'
474. 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 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
80Lư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
>>> 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'
474, >>> 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'
473 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2:Trong hoạt động
>>> 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'
484 mới nhất, bạn sử dụng biểu mẫ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'
493. 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.comprehension. A comprehension is a compact way to process all or part of the elements in a collection or sequence. You can use comprehensions to create lists, dictionaries, and sets.
Các hệ thống bao gồm một cặp dấu ngoặc (
>>> 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'
494) hoặc niềng răng xoă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'
495) chứa một biểu thức, tiếp theo là một hoặc nhiều điều khoản ____296 và sau đó không hoặc một mệnh đề >>> 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'
497 trên mệ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'
496.Điều khoả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'
496 trong một sự hiểu biết hoạt động tương tự như vò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'
496 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 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
81Lư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
>>> 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'
474, >>> 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'
473 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2:Trong hoạt động
>>> 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'
484 mới nhất, bạn sử dụng biểu mẫ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'
493. 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.>>>
>>> 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
82Lư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
>>> 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'
474, >>> 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'
473 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2:Trong hoạt động
>>> 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'
484 mới nhất, bạn sử dụng biểu mẫ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'
493. 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ườngexception variable. The exception variable is a variable that
holds a reference to the exception raised by a >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
805 statement. In Python 3.x, such variables are local to the >>> 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
806 block and are forgotten when the block ends. Check out the following code:>>>
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
83Lư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
>>> 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'
474, >>> 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'
473 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2:Trong hoạt động
>>> 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'
484 mới nhất, bạn sử dụng biểu mẫ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'
493. 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.>>>
>>> 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
84Lư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
>>> 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'
474, >>> 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'
473 sẽ giữ một danh sách các giá trị lớn hơn và lớn hơn. Hãy xem mã sau để thực hiện thay thế bằng cách sử dụng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
2:Lưu ý rằng điều này chỉ áp dụng cho toàn bộ. Khi nói đến các vòng lặp >>> def square(base): ... result = base ** 2 ... print(f'The square of {base} is: {result}') ... >>> square(10) The square of 10 is: 100 >>> result # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in result NameError: name 'result' is not defined >>> base # Isn't accessible from outside square() Traceback (most recent call last): File "", line 1, in base NameError: name 'base' is not defined >>> square(20) The square of 20 is: 400 96 thông thường, biến vòng lặp giữ giá trị cuối cùng được xử lý bởi vòng lặp:
Bạn có thể tự do truy cập biến vòng lặp
>>> def 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
801 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 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
804 trong ví dụ này.L level. L level. Phạm vi biến ngoại lệclass attributes live. Check out this code:class attributes live. Check out this code:
>>>
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
85Khi bạn chạy danh sách hiểu, biế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, in
NameError: name 'inner_func' is not defined
801 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
>>> 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'
496 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 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
86Khi bạn chạy danh sách hiểu, biế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, in
NameError: name 'inner_func' is not defined
801 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
>>> 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'
496 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 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
87Khi bạn chạy danh sách hiểu, biế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, in
NameError: name 'inner_func' is not defined
801 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 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
88Khi bạn chạy danh sách hiểu, biế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, in
NameError: name 'inner_func' is not defined
801 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 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.
>>> 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'
496 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: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 >>>
Khi bạn chạy danh sách hiểu, biếnLư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
>>> 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'
496 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: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 >>>
>>> 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 chạy danh sách hiểu, biế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, in
NameError: name 'inner_func' is not defined
801 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
>>> 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'
496 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:
89instance local scope or namespace first.instance local scope or namespace first.>>> 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 - Lớp
8 26 có một đối số gọi là>>> 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
028, được tự động tăng gấp đôi bên trong>>> 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'
843 bằng cách sử dụng thao tác gá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
844. 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, inNameError: name 'inner_func' is not defined
41 trê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'
846, 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 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
028, có giá trị hiện là>>> 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'
442.class local scope or namespace.class local scope or namespace.>>> 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'
- 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
843. Hãy xem phiên bản mới này của>>> def outer_func(): ... # This block is the Local scope of outer_func() ... var = 100 # A nonlocal var ... # It's also the enclosing scope of inner_func() ... def inner_func(): ... # This block is the Local scope of inner_func() ... print(f"Printing var from inner_func(): {var}") ... ... inner_func() ... print(f"Printing var from outer_func(): {var}") ... >>> outer_func() Printing var from inner_func(): 100 Printing var from outer_func(): 100 >>> inner_func() Traceback (most recent call last): File "
" , line 1, inNameError: name 'inner_func' is not defined
826:>>> 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
831.>>> 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
831.>>> 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
Tại đây, bạn sửa đổi
>>> 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
826 để thêm một phương thức mới gọi là >>> 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
852. Sau đó, bạn tạo một thể hiện là >>> 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
826 bằng cách chuyển 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
12 cho trình khởi tạo lớp. Sau đó, bây giờ bạn có thể gọi >>> 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
852 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, in
NameError: name 'inner_func' is not defined
846 để nhân đôi giá trị được lưu trữ 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
857. Cuối cùng, nếu bạn cố gắng truy cậ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'
028 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 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
831 vì các thuộc tính thể hiện có thể được truy cập bằng cách sử dụng các đối tượng lớp.Nói chung, khi bạn viết mã hướng đối tượng bằng Python và bạn cố gắng truy cập một thuộc tính, chương trình của bạn thực hiện các bước sau:
>>>
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
1Kiểm tra phạm vi địa phương hoặc không gian tên trước.
Nếu thuộc tính không được tìm thấy ở đó, thì hãy kiểm tra phạm vi hoặc không gian tên cục bộ của lớp.
>>>
>>> square.__code__.co_varnames
('base', 'result')
>>> square.__code__.co_argcount
1
>>> square.__code__.co_consts
(None, 2, 'The square of ', ' is: ')
>>> square.__code__.co_name
'square'
2Kiểm tra phạm vi địa phương hoặc không gian tên trước.
>>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'inner_func' is not defined
831.- 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. Use
857 to access this attribute.>>> 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 - Nếu tên không tồn tại trong không gian tên lớp, thì bạn sẽ nhận được Use
868 to access this attribute.>>> 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
Đây là cơ chế cơ bản mà Python giải quyết các tên trong các lớp học và trường hợp. Use
>>> def 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
857 to access this attribute.Mặc dù các lớp xác định phạm vi hoặc không gian tên cục bộ lớp, nhưng chúng không tạo ra phạm vi kèm theo các phương thức. Do đó, khi bạn thực hiện một lớp, các tham chiếu đến các thuộc tính và phương thức phải được thực hiện bằng cách sử dụng ký hiệu chấm: Use >>> def 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
868 to access this attribute.Vì các lớp don lồng tạo ra một phạm vi kèm theo cho các phương thức, bạn có thể truy cập
>>> 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'
028 trực tiếp từ trong vòng >>> def outer_func():
... # This block is the Local scope of outer_func()
... var = 100 # A nonlocal var
... # It's also the enclosing scope of inner_func()
... def inner_func():
... # This block is the Local scope of inner_func()
... print(f"Printing var from inner_func(): {var}")
...
... inner_func()
... print(f"Printing var from outer_func(): {var}")
...
>>> outer_func()
Printing var from inner_func(): 100
Printing var from outer_func(): 100
>>> inner_func()
Traceback (most recent call last):
File "", line 1, in
NameError: name 'inner_func' is not defined
862 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 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
863 bên 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
862 thà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
865 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: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.
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. advantage of Python scope to avoid or minimize bugs related to name collision
- Bây giờ bạn có thể: good use of global and local names across your programs to improve code maintainability
- 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 a coherent strategy to access, modify, or update names across all your Python code
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!The region where an object is visible is referred to as its scope.
Các loại phạm vi trong Python là gì?
Bạn sẽ tìm hiểu về bốn phạm vi khác nhau với sự trợ giúp của các ví dụ: địa phương, bao quanh, toàn cầu và tích hợp.Các phạm vi này cùng nhau tạo thành cơ sở cho quy tắc LEGB được sử dụng bởi trình thông dịch Python khi làm việc với các biến.local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.
Quy tắc phạm vi trong Python là gì?
Quy tắc LEGB đặt tên cho các phạm vi có thể có của một biến trong Python: Local, bao quanh, toàn cầu, tích hợp.Python tìm kiếm các không gian tên theo thứ tự này để xác định giá trị của một đối tượng được đặt tên.Phạm vi được tạo ra với các chức năng, lớp và mô -đun.
Phạm vi của các biến trong Python là gì?
Một biến chỉ có sẵn từ bên trong khu vực nó được tạo ra.Đây được gọi là phạm vi.. This is called scope.. This is called scope.