Home > Backend Development > Python Tutorial > Detailed explanation of five knowledge points to easily understand the scope of Python

Detailed explanation of five knowledge points to easily understand the scope of Python

高洛峰
Release: 2017-03-28 15:09:57
Original
1323 people have browsed it

There are many introductions about Python scope on the Internet, so the article I will share with you today allows you to easily understand Python scope by learning these 5 knowledge points. Friends in need can refer to it. Learn from.

">

1. Block-level scope

Think about whether there will be output when running the following program at this time? Will the execution be successful?

#Block-level scope

if 1 == 1:
name = "lzl"

print(name)


for i in range( 10):
age = i

print(age)

Let’s take a look at the execution results first

C:/Users/L/PycharmProjects/s14/preview/ Day8/Scope/main.py
lzl
9

Process finished with exit code 0

The code is executed successfully, no problem; in Java/C#, execute the above The code will prompt that name and age are not defined, but it can be executed successfully in Python. This is because there is no block-level scope in Python. The variables in the code block can be called externally, so it can run successfully;

2. Local scope

Looking back on the knowledge we have learned before, when we learned functions, the function was a separate scope. There is no block-level scope in Python, but there is a local scope; take a look below Code

#Local scope

def func():
name = "lzl"

print(name)

Run this section Code, think about whether there will be output?

Traceback (most recent call last):
File "C:/Users/L/PycharmProjects/s14/preview/Day8/scope/main.py ", line 23, in
print(name)
NameError: name 'name' is not defined

Running error, I believe everyone can understand this, the name variable is only in The func() function takes effect internally, so it cannot be called globally; make a simple adjustment to the above code and see what the result is?

#Local scope

def func ():
name = "lzl"

func() #Execute function
print(name)

Added a code to the previous code, before printing the variable name , execute the function, will the printing change at this time?

Traceback (most recent call last):
File "C:/Users/L/PycharmProjects/s14/preview/Day8/effect? Domain/main.py", line 23, in
print(name)
NameError: name 'name' is not defined

The execution still reports an error, so go back to the previous sentence Words: Even if the function is executed, the scope of name is only inside the function, and it still cannot be called from the outside; remember the first two knowledge points, and then start to expand the trick

3. Scope Chain

Adjust the function and see what the execution result of the following code is?

#Scope chain

name = "lzl"
def f1():
name = "Eric"
def f2():
name = "Snor"
print(name)
f2()
f1()

If you have learned functions, you must know that Snor will be output after f1() is executed; let’s remember a concept first , there is a scope chain in Python. Variables will be searched from inside to outside. First go to your own scope to find it. You will not go to the superior to find it until you can’t find it and report an error.

4. Ultimate Edition Scope

Okay, enough foreshadowing, the Ultimate Edition is here~~

# Ultimate Edition Scope

name = "lzl"

def f1( ):
print(name)

def f2():
name = "eric"
f1()

f2()

Think Do you want to print "lzl" or "eric" as the final execution result of f2()? Remember your answer. Instead of posting the answer now, take a look at the following code:

#Ultimate Edition Scope

name = "lzl"

def f1():
print(name)

def f2():
name = "eric"
return f1

ret = f2()
ret()

#Output: lzl

The execution result is "lzl". Analyzing the above code, the execution result of f2() is the memory address of function f1, that is, ret=f1; execute ret() is equivalent to executing f1(). When executing f1(), it has nothing to do with f2(). name="lzl" and f1() are in the same scope chain. If there is no variable inside the function, it will be looked for outside, so this The value of the time variable name is "lzl"; if you understand this, then you also know the answer to the ultimate code that the answer was not given just now

# Ultimate Edition Scope

name = "lzl"

def f1():
print(name)

def f2():
name = "eric"
f1()

f2 ()

# Output: lzl

Yes, the output is "lzl", remember that before the function is executed, the scope has been formed and the scope chain has also been generated

5, Sina interview questions

li = [lambda :x for x in range(10)]

Determine the type of li? What type are the elements in li?

print(type(li))
print(type(li[0]))

#
#

You can see that li is a list type and the elements in the list are functions. Then print the return value of the first element in the list. What is the return value at this time?

#lambada interview questions

li = [lambda :x for x in range(10)]

res = li[0]()
print(res )

#Output: 9

liThe return value of the first function is 9, not 0. Remember: the internal code will not be executed before the function is executed; the code in the blog can Practice it yourself and deepen your impression

Summary

The above is the entire content of this article. I don’t know if it can bring some help to everyone’s study and work. If you have any questions, you can Leave messages to communicate.

The above is the detailed content of Detailed explanation of five knowledge points to easily understand the scope of Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template