Difference between _, __ and __xx__ in Python

When learning Python many people don‘t really understand why so much underlines in the beginning of the methods, sometimes

even in the end like __this__! I‘ve already had to explain it so many times, it‘s time to document it.

One underline in the beginning

Python doesn‘t have real private methods, so one underline in the beginning of a method or attribute means you shouldn‘t access

this method, because it‘s not part of the API. It‘s very common when using properties:

class BaseForm(StrAndUnicode):
    ...

    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors is None:
            self.full_clean()
        return self._errors

    errors = property(_get_errors)

This snippet was taken from django source code (django/forms/forms.py). This means errors is a property, and it‘s part of the API,

but the method this property calls, _get_errors, is "private", so you shouldn‘t access it.

Two underlines in the beginning

This one causes a lot of confusion. It should not be used to mark a method as private, the goal here is to avoid your method to be

overridden by a subclass. Let‘s see an example:

class A(object):
    def __method(self):
        print "I‘m a method in A"

    def method(self):
        self.__method()

a = A()
a.method()

The output here is

$ python example.py
I‘m a method in A

Fine, as we expected. Now let‘s subclass A and customize __method

class B(A):
    def __method(self):
        print "I‘m a method in B"

b = B()
b.method()

and now the output is...

$ python example.py
I‘m a method in A

as you can see, A.method() didn‘t call B.__method() as we could expect. Actually this is the correct behavior for __. So when you create

a method starting with __ you‘re saying that you don‘t want anybody to override it, it will be accessible just from inside the own class.

How python does it? Simple, it just renames the method. Take a look:

a = A()
a._A__method()  # never use this!! please!
$ python example.py
I‘m a method in A

If you try to access a.__method() it won‘t work either, as I said, __method is just accessible inside the class itself.

Two underlines in the beginning and in the end

When you see a method like __this__, the rule is simple: don‘t call it. Why? Because it means it‘s a method python calls, not you.

Take a look:

>>> name = "igor"
>>> name.__len__()
4
>>> len(name)
4

>>> number = 10
>>> number.__add__(20)
30
>>> number + 20
30

There is always an operator or native function that calls these magic methods. The idea here is to give you the ability to override

operators in your own classes. Sometimes it‘s just a hook python calls in specific situations. __init__(), for example, is called when

the object is created so you can initialize it. __new__() is called to build the instance, and so on...

Here‘s an example:

class CrazyNumber(object):

    def __init__(self, n):
        self.n = n

    def __add__(self, other):
        return self.n - other

    def __sub__(self, other):
        return self.n + other

    def __str__(self):
        return str(self.n)

num = CrazyNumber(10)
print num           # 10
print num + 5       # 5
print num - 20      # 30

Another example:

class Room(object):

    def __init__(self):
        self.people = []

    def add(self, person):
        self.people.append(person)

    def __len__(self):
        return len(self.people)

room = Room()
room.add("Igor")
print len(room)     # 1

The documentation covers all these special methods.

时间: 2024-10-21 07:23:34

Difference between _, __ and __xx__ in Python的相关文章

python中_、__和__xx__的区别

python中_.__和__xx__的区别 本文为译文,版权属于原作者,在此翻译为中文分享给大家. 英文原文地址:Difference between _, __ and __xx__ in Python 在学习Python时,很多人都弄不清楚各种下划线的意思,而且在这之前已经给其他人解释过很多遍了,是时候把它记录下来. "_"单下划线 Python中不存在真正的私有方法.为了实现类似于c++中私有方法,可以在类的方法或属性前加一个“_”单下划线,意味着该方法或属性不应该去调用,它并不

python _、__和__xx__的区别

本文为译文,版权属于原作者,在此翻译为中文分享给大家.英文原文地址:Difference between _, __ and __xx__ in Python "_"单下划线 Python中不存在真正的私有方法.为了实现类似于c++中私有方法,可以在类的方法或属性前加一个“_”单下划线,意味着该方法或属性不应该去调用,它并不属于API. 在使用property时,经常出现这个问题: class BaseForm(StrAndUnicode): ... def _get_errors(s

Python中_,__,__xx__的区别

_xx 单下划线开头 Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范. __xx 双下划线开头 双下划线开头,是为了不让子类重写该属性方法.通过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现. __xx__ 此种写法为python内建属性方法,最好不要在外部调用 参考自:http://blog.csdn.net/wukai_std/article/detai

python _、__、__xx__之间的差别

本文来自 yzl11 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yzl11/article/details/53792416?utm_source=copy 单下划线.双下划线.头尾双下划线说明: 1. __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的. 当你看到"__this__"的时,就知道不要调用它.为什么?因为它的意思是它是用于Python调用的,如下 >>> name = &q

python中_, __, __foo__区别及使用场景

单下划线 1.带有单下划线的特性不会被 from module import *导入. 2.单下划线是Python程序员使用类时的约定,表明程序员不希望类的用户直接访问属性.仅仅是一种约定!实际上,实例._变量,可以被访问. 双下划线 1.防止被子类覆盖. 前后双下划线 供python内部使用,如__init__ new str 等. 原文地址:https://www.cnblogs.com/sixloop/p/python_abc.html

Python下划线的使用 _ __ __obj__

Python 用下划线作为变量前缀和后缀指定特殊变量. _xxx 不能用'from moduleimport *'导入 __xxx__ 系统定义名字 __xxx 类中的私有变量名 核心风格:避免用下划线作为变量名的开始. 因为下划线对解释器有特殊的意义,而且是内建标识符所使用的符号,我们建议程序员避免用下划线作为变量名的开始.一般来讲,变量名_xxx被看作是“私有 的”,在模块或类外不可以使用.当变量是私有的时候,用_xxx 来表示变量是很好的习惯.因为变量名__xxx__对Python 来说有

Python学习笔记_零零一:Python基本介绍

Python介绍 Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言.Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构.Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节.类似于PHP和Perl语言.Python 是交互式语言: 这意味着,您可以在一个Python提示符,直接互动执行写你的程序.Python 是面向对象语言: 这意味着Python支持面向对象的风格或代码封装

高精度_百炼_大整数除法 2737 (Python)

a=input() a=int(a) b=input() b=int(b) print(a//b) print("\n") 原文地址:https://www.cnblogs.com/MapReduce/p/8394534.html

计量经济与时间序列_自协方差(AutoCovariance)算法解析(Python)

1 样本的自协方差函数的通式如下: 2 其实,后面要计算的自相关函数也可以用自协方差来表示: 1 TimeSeries = [11.67602657, 5.637492979, 1.375516942, 0.618705492, -0.152047234, -0.508555434, -6.065288121, -9.417602801, 2 -10.47205437, -8.018063902, 0.523277554, 4.86893283, 4.23977562, -10.2344375,