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 #
print num + 5 #
print num - 20 #
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) #
The documentation covers all these special methods.
Difference between _, __ and __xx__ in Python的更多相关文章
- python _、__和__xx__的区别
python _.__和__xx__的区别 本文为译文,版权属于原作者,在此翻译为中文分享给大家.英文原文地址:Difference between _, __ and __xx__ in Pytho ...
- Python中_,__,__xx__的区别
_xx 单下划线开头 Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范. #! /usr ...
- Difference between exit() and sys.exit() in Python
Difference between exit() and sys.exit() in Python - Stack Overflow https://stackoverflow.com/questi ...
- python _、__和__xx__的区别(转)
本位转载自:http://www.cnblogs.com/coder2012/p/4423356.html "_"单下划线 Python中不存在真正的私有方法.为了实现类似于c++ ...
- python中 _、__、__xx__() 区别及使用场景
1.访问权限(private.public)与继承方式(只有public继承) 在面向对象编程语言中,类的属性与方法都会设置访问控制权限,从而满足我们的设计需求.一般而言,我们通常会将对象的属性设置为 ...
- Python中_,__,__xx__方法区别
_xx 单下划线开头 Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范. 方法就是以单下 ...
- 【python】python _、__、__xx__之间的差别
本文来自 yzl11 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yzl11/article/details/53792416?utm_source=copy 单下 ...
- python _、__、__xx__之间的差别
默认情况下,Python中的成员函数和成员变量都是公开的(public),在python中没有类public,private等关键词来修饰成员函数和成员变量.其实,Python并没有真正的私有化支持, ...
- python中_、__、__xx__(单下划线、双下划线等)的含义
(1)_xxx "单下划线 " 开始的成员变量相当于私有变量,也叫做保护变量,意思是只有类实例和子类实例能访问到这些变量,需通过类提供的接口进行访问(可以定义有点像java中的ge ...
随机推荐
- PDA手持终端集成一体打印 二次开发
PDA手持终端集成一体打印 二次开发支持 VS2008或VS2005开发工具 c#或C++开发语言 Mobile6.5,支持GSM通话,GPRS,EDGE网络;内置wifi,蓝牙,gps商场单品管理小 ...
- MAXIMO移动解决方案在库存管理中的PDA应用系统
随着无线网络通信技术.掌上电脑技术以及条形码自动识别技术的推广使用,为了强化MAXIMO系统库存管理的功能,着手开发MAXIMO移动应用解决方案. 该解决方案集成了无线局域网络通信.掌上电脑以及条形码 ...
- DFS(剪枝) POJ 1011 Sticks
题目传送门 /* 题意:若干小木棍,是由多条相同长度的长木棍分割而成,问最小的原来长木棍的长度: DFS剪枝:剪枝搜索的好题!TLE好几次,终于剪枝完全! 剪枝主要在4和5:4 相同长度的木棍不再搜索 ...
- 推荐一个非常COOL的开源相册程序!
不知道大家有没想过有一个完全属于自己的网络相册?现在网上的相册程序已可以说多不胜数,那么到底要使用哪个会比较好呢? 之前我也在为此事烦恼过,在网上找了很多个程序试了,但都没达到我的要求,后来发终于功夫 ...
- TYVJ P1067 合唱队形 Label:上升子序列?
背景 NOIP2004 提高组 第三道 描述 N位同学站成一排,音乐老师要请其中的(N-K)位同学出列,使得剩下的K位同学排成合唱队形. 合唱队形是指这样的一种队形:设K位同学从左到右依次编号 ...
- 【BZOJ】1146: [CTSC2008]网络管理Network(树链剖分+线段树套平衡树+二分 / dfs序+树状数组+主席树)
http://www.lydsy.com/JudgeOnline/problem.php?id=1146 第一种做法(时间太感人): 第二种做法(rank5,好开心) ================ ...
- 冒泡排序:一百以内十个随机数放入数组排序并打印<
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- string.h文件中函数用法
下面为string.h文件中函数的详细用法: strcpy函数名:strcpy功 能: 拷贝一个字符串到另一个用 法: char *strcpy(char *destin, char *source) ...
- jquery CDN(内容分发网络)使用
jquery CDN 给开发者提供一种捷径,即不下载jquary 就通过CDN能使用各个版本的jquery. 使用方法很简单,就是在HTML 文档中引用相关版本的jquery. 例如:我用百度的CDN ...
- maven相关概念
1.maven仓库分为:本地仓库,远程仓库.远程仓库分为私服.中央仓储和其他公共库. 2.mvn clean install 部署到本地仓库 3.mvn clean deploy 部署到远程仓储 4. ...