阅读目录

楔子

假如有一个函数,实现返回两个数中的较大值:

def my_max(x,y):
    m = x if x>y else y
    return m
bigger = my_max(10,20)
print(bigger)

之前是不是我告诉你们要把结果return回来你们就照做了?可是你们有没有想过,我们为什么要把结果返回?如果我们不返回m,直接在程序中打印,行不行?

来看结果:

>>> def my_max(x,y):
...     m = x if x>y else y
... 
>>> my_max(10,20)
>>> print(m)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'm' is not defined

报错了!错误是“name 'm' is not defined”。变量m没有被定义。。。为啥?我明明定义了呀!

在这里我们首先回忆一下python代码运行的时候遇到函数是怎么做的。

从python解释器开始执行之后,就在内存中开辟了一个空间

每当遇到一个变量的时候,就把变量名和值之间的对应关系记录下来。

但是当遇到函数定义的时候解释器只是象征性的将函数名读入内存,表示知道这个函数的存在了,至于函数内部的变量和逻辑解释器根本不关心。

等执行到函数调用的时候,python解释器会再开辟一块内存来存储这个函数里的内容,这个时候,才关注函数里面有哪些变量,而函数中的变量会存储在新开辟出来的内存中。函数中的变量只能在函数的内部使用,并且会随着函数执行完毕,这块内存中的所有内容也会被清空。

我们给这个“存放名字与值的关系”的空间起了一个名字——叫做命名空间

代码在运行伊始,创建的存储“变量名与值的关系”的空间叫做全局命名空间,在函数的运行中开辟的临时的空间叫做局部命名空间

命名空间和作用域

命名空间的本质:存放名字与值的绑定关系

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
python之禅

相关文章:

  • 2021-03-27
  • 2021-04-29
  • 2021-11-23
  • 2020-04-08
  • 2019-07-29
  • 2021-06-25
  • 2021-04-17
猜你喜欢
  • 2020-05-22
  • 2018-06-28
  • 2018-09-15
  • 2019-11-08
  • 2018-10-15
  • 2021-08-02
  • 2018-09-10
  • 2020-03-21
相关资源
相似解决方案