Underscores in Python https://shahriar.svbtle.com/underscores-in-python

Underscores in Python

This post discusses the use of the _ character in Python. Like with many things in Python, we’ll see that different usages of _ are mostly (not always!) a matter of convention.

Single Lone Underscore (_)

This is typically used in 3 cases:

  1. In the interpreter: The _ name points to the result of the last executed statement in an interactive interpreter session. This was first done by the standard CPython interpreter, and others have followed too.

    >>> _
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name '_' is not defined
    >>> 42
    >>> _
    42
    >>> 'alright!' if _ else ':('
    'alright!'
    >>> _
    'alright!'
  2. As a name: This is somewhat related to the previous point. _ is used as athrow-away name. This will allow the next person reading your code to know that, by convention, a certain name is assigned but not intended to be used. For instance, you may not be interested in the actual value of a loop counter:

    n = 42
    for _ in range(n):
    do_something()
  3. i18n: One may also see _ being used as a function. In that case, it is often the name used for the function that does internationalisation and localisation string translation lookups. This seems to have originated from and follow the corresponding C convention.
    For instance, as seen in the Django documentation for translation, you may have:

    from django.utils.translation import ugettext as _
    from django.http import HttpResponse def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

The second and third purposes can conflict, so one should avoid using _ as a throw-away name in any code block that also uses it for i18n lookup and translation.

Single Underscore Before a Name (e.g. _shahriar)

A single underscore before a name is used to specify that the name is to be treated as “private” by a programmer. It’s kind of* a convention so that the next person (or yourself) using your code knows that a name starting with _is for internal use. As the Python documentation notes:

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.

* I say kind of a convention because it actually does mean something to the interpreter; if you from <module/package> import *, none of the names that start with an _ will be imported unless the module’s/package’s __all__ list explicitly contains them. See “Importing * in Python” for more on this.

Double Underscore Before a Name (e.g. __shahriar)

The use of double underscore (__) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses. As the Python documentation notes, any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, whereclassname is the current class name with leading underscore(s) stripped.

Take the following example:

>>> class A(object):
... def _internal_use(self):
... pass
... def __method_name(self):
... pass
...
>>> dir(A())
['_A__method_name', ..., '_internal_use']

As expected, _internal_use doesn’t change but __method_name is mangled to _ClassName__method_name. Now, if you create a subclass of A, say B(argh, bad, bad names!) then you can’t easily override A‘s __method_name:

>>> class B(A):
... def __method_name(self):
... pass
...
>>> dir(B())
['_A__method_name', '_B__method_name', ..., '_internal_use']

The intended behaviour here is almost equivalent to final methods in Java and normal (non-virtual) methods in C++.

Double Underscore Before and After a Name (e.g.__init__)

These are special method names used by Python. As far as one’s concerned, this is just a convention, a way for the Python system to use names that won’t conflict with user-defined names. You then typically override these methods and define the desired behaviour for when Python calls them. For example, you often override the __init__ method when writing a class.

There is nothing to stop you from writing your own special-method-looking name (but, please don’t):

>>> class C(object):
... def __mine__(self):
... pass
...
>>> dir(C)
... [..., '__mine__', ...]

It’s easier to stay away from this type of naming and let only Python-defined special names follow this convention.

https://docs.djangoproject.com/en/2.0/intro/tutorial01/

[root@hadoop3 pydataweb]# tree
.
└── mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py

2 directories, 5 files
[root@hadoop3 pydataweb]#

  • mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.

Python魔术方法-Magic Method - j_hao104的个人页面 - 开源中国 https://my.oschina.net/jhao104/blog/779743

Python Tutorial: Magic Methods https://www.python-course.eu/python3_magic_methods.php

Previous Chapter: Multiple Inheritance
Next Chapter: OOP, Inheritance Example

Magic Methods and Operator Overloading

_ 下划线 Underscores __init__的更多相关文章

  1. golang _下划线占位符代替需要释放的资源的问题

    golang中_有两种作用,一种用在import中,比如这样 import _ "github.com/go-sql-driver/mysql" 表示并不需要导入整个包,只是执行这 ...

  2. Scala中_(下划线)的常见用法

    Scala中_(下划线)的常见用法 地址:https://www.jianshu.com/p/0497583ec538

  3. _ 下划线 vue mixins 混入 变量前有下划线 变量不起作用

    _ 下划线 vue mixins 混入 变量前有下划线 变量不起作用

  4. fastjson简单使用demo,@JSONField注解属性字段上与set、get方法上。实体类toString(),实体类转json的区别;_下划线-减号大小写智能匹配

    一.demo代码 @JSONField注解属性字段上与set.get方法上.使用@Data注解(lombok插件安装最下方),对属性“笔名”[pseudonym]手动重写setter/getter方法 ...

  5. python 类相关 下划线相关 __init__

    类 1.静态方法 class C(object): @staticmethod def f(): print('runoob'); C.f(); # 静态方法无需实例化 cobj = C() cobj ...

  6. python实现将字符串中以大写字母开头的单词前面添加“_”下划线

    在工作中写测试用例代码生成的时候,函数命令考虑采用参数文件的名称来命名,但是发现文件命名是驼峰的写写法,所以想按照字符串中的大写字母做分割,每个单词前面添加下划线,主要考虑采用正则的模式来匹配,替换然 ...

  7. Scala _ 下划线

    1.引入包中的全部方法 import math._ //引入包中所有方法,与java中的*类似 2.表示集合元素 val a = (1 to 10).filter(_%2==0).map(_*2) / ...

  8. Scala 神奇的下划线 _

    引言 在 Scala 中,下划线 _ 有很多种用法,作为 Scala 初学者也经常被下划线 _ 搞得晕头转向,下面是对 Scala 中下划线 _ 使用的简单总结~ 导包时, 下划线 _ 表示引用多个方 ...

  9. Python 中奇妙的下划线

    单个下划线(_) 通常有三种用法: 在python解释器: 单个下划线代表上次在交互解释期对话中(控制台)执行的结果.这种情况在标准的CPython解释器中首次被实现,接下来这种习惯也被保持下来: & ...

随机推荐

  1. Android中Scrollview、ViewPager冲突问题汇总(已解决)

    显示问题: 1.设置ScrollView的fillViewPort为true 2.设置ViewPager的layout_height为一个固定高度,比如:100dip 冲突问题: 不过ViewPage ...

  2. Android Viewpager实现图片轮播(仿优酷效果)

    1 http://blog.csdn.net/t12x3456/article/details/8160128 2 http://www.cnblogs.com/androidez/archive/2 ...

  3. asp.net core mvc视频A:笔记5-1.路由规则

    方法一:通过MapRoute方法,配置文件位置 小例子:如果所有路径都要在admin下,可以这样写 方法二:通过路由属性 相对路由 现在需要加/admin/home/index才能正常访问原来的默认页 ...

  4. vmware安装问题:Microsoft Runtime DLL安装程序未能完成安装

    下载vmware station 12 pro后安装,发现有以下问题:   解决方法: 在提示这个页面的时候,在运行中输入: %temp%   在打开来的文件窗口中,找到末尾为 ~setup的文件夹, ...

  5. rsync权限操作

    rsync对目的端权限如果不使用 -a 或者-p   -a=-rlptgoD 目的端的目录和文件权限不会改变 同步过程中改变目录和文件权限用法: rsync -rltDvP --chmod=Dugo= ...

  6. CSS实现子级窗口高度随低级窗口高度变化及js控制左右容器高度一致

    纯粹使用使用height:100%;或者height:auto;来定义内部容器自适应高度,都无法实现让内部容器高度随着外部父容器高度变化而变化,所以我们必需要使用position绝对定位属性来配合协助 ...

  7. Mysql中处理1970年前的日期(unixtime为负数的情况)负数时间戳格式化

    客户扔过来一个bug,说是一个系统中对42岁以上的人的统计不正确,而41岁以下的人没有问题.眼睛瞟了一下托盘区里的日期,2012年3月26日,嗯,今年42岁的话,那么应该就是出生在1970年左右,马上 ...

  8. FromHBITMAP 这个函数会丢失透明信息。

    在用 FromHBITMAP 你会发现出来的图是带有黑边的,这是因为这个函数有个 bug,解决的办法是用下列的函数进行转换,大体意思就是自己 memcpy 不要用 FromHBITMAP 函数. Bi ...

  9. jedis连接池的参数配置

     <!-- 连接池的配置信息 --> <bean id="jedisConfig" class="redis.clients.jedis.Jedis ...

  10. oracle命令登录数据库

    sqlplus aa/aa@jdbc:oracle:thin:@10.200.130.111:1521:nbact 或者 sqlplus aa/aa@nbact