Python中的单下划线和双下划线使用场景详解

发布时间:2020-09-07 07:18:10 作者:Mr汪
来源:脚本之家 阅读:160

单下划线

单下划线用作变量

最常见的一种使用场景是作为变量占位符,使用场景明显可以减少代码中多余变量的使用。为了方便理解,_可以看作被丢弃的变量名称,这样做可以让阅读你代码的人知道,这是个不会被使用的变量,e.g.。

for _, _, filenames in os.walk(targetDir):
  print(filenames)
  
for _ in range(100):
  print('PythonPoint')

在交互解释器比如iPython中,_变量指向交互解释器中最后一次执行语句的返回结果。

单下划线前缀名称(例如_pythonPoint)

单下划线后缀名称

通常用于和Python关键词区分开来,比如我们需要一个变量叫做class,但class是Python的关键词,就可以以单下划线结尾写作class_

双下划线

双下划线前缀名称

这表示这是一个私有成员(属性或者方法)。它无法直接像公有成员一样随便访问。双下划线开头的命名形式在Python的类成员中使用表示名字改编,即如果Test类里有一成员__x,那么dir(Test)时会看到_Test__x而非__x。这是为了避免该成员的名称与子类中的名称冲突,方便父类和子类中该成员的区分识别。但要注意这要求该名称末尾最多有一个下划线。e.g.

Python中的单下划线和双下划线使用场景详解

双下划线前缀及后缀名称

一种约定,Python内部的名字,用来区别其他用户自定义的命名,以防冲突。是一些Python的“魔术”对象,表示这是一个特殊成员。如类成员的__init____del____add__等,以及全局的__file____name__等。Python官方推荐永远不要将这样的命名方式应用于自己的变量或函数,而是按照文档说明来使用Python内置的这些特殊成员。

Python中关于私有属性、方法约定问题,官方文档如下

“Private” instance variables that cannot be accessed except from inside an object don't exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form__spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 怎么在python中使用单下划线(_)和双下划线(__)
  2. Python3中_(下划线)和__(双下划线)的用途和区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 单下划线 双下划线

上一篇:vue加载自定义的js文件方法

下一篇:iOS自定义UIDatepicker日期选择器视图分享

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》