python:_, __ 和__xx__辨异
来源:互联网 发布:android 7.0源码分析 编辑:程序博客网 时间:2024/06/07 22:19
One underline in the beginning
Python实际上并没有私有方法,在方法/属性开头的下划线意味着:不要访问该方法,表明这个方法并非API的一部分。
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)
errors是属性,属于API的一部分;而它调用的方法
_get_errors是类的私有方法,所以是不能为访问到的。
Two underlines in the beginning
在开头有双下划线目的是避免该方法被子类覆盖,请不要把该方法标记为private。
class A(object): def __method(self): print "I'm a method in A" def method(self): self.__method() a = A()a.method()
输出为:
$ python example.py I'm a method in A
让我们再来定义A的子类并且定义__method方法,
class B(A): def __method(self): print "I'm a method in B"b = B()b.method()
则输出为:
$ python example.pyI'm a method in A
可见,A.method()
并未调用B.__method()
。也就是说,如果你创建
以
__开头的
方法名
,也就意味着你不希望任何人覆盖这个方法,只能在该类中访问到该方法。
a = A()a._A__method() # never use this!! please!
$ python example.pyI'm a method in A
Two underlines in the beginning and in the end
如果一个方法的形式好像 __this__,规则就简单了:请勿创建。
>>> name = "igor">>> name.__len__()4>>> len(name)4>>> number = 10>>> number.__add__(20)30>>> number + 2030
比如在创建对象时python调用
__init__();在建实例时,python会调用__new__()。
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 # 10print num + 5 # 5print num - 20 # 30
另一个例子,
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
文档 集中了所有这些特殊方法。
- python:_, __ 和__xx__辨异
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- Python中_,__,__xx__的区别
- Python中_,__,__xx__的区别
- python中下划线,双下划线,首尾双下划线的区别(Difference between _, __ and __xx__ in Python)
- python中下划线,双下划线,首尾双下划线的区别(Difference between _, __ and __xx__ in Python)
- PYTHON类中“__”和“_”用法小记
- python 之_、__、__xxx__
- Python 辨异 —— __init__ 与 __new__
- 辨异 —— 逻辑之辨
- 关于PS降噪的两种方法
- Hello World
- android 对话框大全
- C++多文件项目编译
- ssh 事务不能回滚 Could not roll back Hibernate transaction; nested exception is org.hibernate.Transaction
- python:_, __ 和__xx__辨异
- SQL SERVER 合并重复行,行列转换(sql server2000 里面如何实现oracle10g的 wmsys.wm_concat() 的功能?)
- dropdownlist绑定的二种方法
- HDU1391:Number Steps
- jquery validate(4) : 写自定义验证
- 命令行下Android AVD命令解析
- 插值方法-效率高的插值方法-opencv(二)
- 强大无比的android智能开发平台--imx6Q+android4.x
- C语言下取得系统开机运行时间