1
Python中的下划线有多少种用法和含义?
source link: https://greyli.com/underscore-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python中的下划线有多少种用法和含义?
这篇文章来自我在知乎上的这个回答,做个备份。
大概有10种。
# No.1
# 在交互式解释器中获取上一个语句执行的结果
# >>> 1+1
# >>> _
# >>> _ * 5
# No.2
# 用来在函数、模块、包、变量名中分隔单词,增加可读性
var_foo_bar
# No.3
# 内部使用的变量、属性、方法、函数、类或模块(约定)
# from foo import * 不会导入以下划线开头的对象
# No.4
# 避免和保留的关键字冲突(约定)
# 比如:class_、type_
# No.5
# 在类内的私有变量(private)
# 类外部无法直接使用原名称访问
# 需要通过instance._ClassName__var的形式访问(name mangling)
__var
# No.6(这一条存疑)
# 在类内的保护变量
_var_
# No.7
# Python内置的“魔法”方法或属性
# 你也可以自己定义,但一般不推荐
# 比如:__init__, __file__, __main__
__var__
# No.8
# 作为内部使用的一次性变量
# 通常在循环里使用
# 比如:[_ for _ in range(10)]
# 或是用作占位,不实际使用的变量
# 比如:for _, a in [(1,2),(3,4)]: print a
# No.9
# i18n里作为gettext()的缩写
# No.10
# 用来分隔数值以增加可读性(Python 3.6新增)
# >>> num = 1_000_000
# >>> num
# 1000000
1_000_000
参考链接:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK