cs自学指南使我快乐。
1.Print and None
首先明确None是什么。课程中原话为“The special value None represents nothing in Python,a function that does not explicitly return a value will return None,None is not displayed by the intepreter as the value of an expression.”。None其实也是一个返回值,但是在终端不可见。有一个很好的例子如下:
>>> def does_not_square(x):
x*x
>> does_not_square(4)
>> sixteen = does_not_square(4)
>> sixteen + 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
这个例子中,函数调用以后实际返回了None,但是实际上由于None is not displayed by the intepreter as the value of an expression,实际上在终端上不可见。而如果用sixteen来接受这个None,再与整型相加就会报错。
>>> print(None,None)
None None
>> print(print(1),print(2))
1
2
None None
>>
可以看见,直接在print里输入None会返回None,这个很好理解。那下面的print嵌套怎么理解呢?
可以把函数分成两类,一种是Pure Functions,just return values,例如 abs( ),pow()等,进去一个argument,出来一个value。
还有一种是Non-Pure Functions,have side effects.print就是一个例子。对于print而言,它返回的value是None,它的side effect 是输出字符,因为它本来就是做这个的。
所以对于print(print(1), print(2))而言,分别执行内层的print(1)和print(2)会输出1和2,而它们的返回值则是None,会作为外层print的参数输出。
2.Environments,Frames,names and values
An environment is a sequence of frames.
A name evaluates to the value bound to that name in the earliest frame of the current environment in which the name is found.
环境(environments),帧(frames),名(names),值(values)。上面的一句话就已经很好的总结了它们之间的关系。
- 绑定 是名字到值的映射。
- 帧 是一组绑定的集合,代表一个作用域。
- 环境 是由多个帧组成的序列,它决定了在程序执行过程中如何查找名字对应的值。这种结构是理解变量作用域、函数调用和闭包的基础。
总是先在最近的帧查找所需要的名,这一点很重要,由此我们就能理解如下代码:
>>> def square(square):
return mul(square, square)
>> square
<function square at 0x100523560>
>> square(4)
16
>>
对于这个例子而言,square在全局环境中是一个函数。但是在调用之后创建了一个新的帧,在新的帧中它被赋值为4。因此在return时直接使用当前帧中的name,正确计算。
评论(1)