2.1 懒人必备技能:使用 “_” |image0| =================================== 对于 ``_`` ,大家对于他的印象都是用于 **占位符**\ ,省得为一个不需要用到的变量,绞尽脑汁的想变量名。 今天要介绍的是他的第二种用法,就是在交互式模式下的应用。 示例如下: .. code:: python >>> 3 + 4 7 >>> _ 7 >>> name='公众号: Python编程时光' >>> name '公众号: Python编程时光' >>> _ '公众号: Python编程时光' 它可以返回上一次的运行结果。 但是,如果是print函数打印出来的就不行了。 .. code:: python >>> 3 + 4 7 >>> _ 7 >>> print("公众号: Python编程时光") ming >>> _ 7 我自己写了个例子,验证了下,用\ ``__repr__``\ 输出的内容可以被获取到的。 首先,在我们的目录下,写一个文件 demo.py。内容如下 .. code:: python # demo.py class mytest(): def __str__(self): return "hello" def __repr__(self): return "world" 然后在这个目录下进入交互式环境。 .. code:: python >>> import demo >>> mt=demo.mytest() >>> mt world >>> print(mt) hello >>> _ world 知道这两个魔法方法的人,一看就明白了,这里不再解释啦。 |image1| .. |image0| image:: http://image.iswbm.com/20200804124133.png .. |image1| image:: http://image.iswbm.com/20200607174235.png