python 类中的 _xx, __xx, __xx__区别
1,区别整理
项目 | 作用 | 类内部使用 | 子类使用 | 作为API使用 | 说明 |
---|---|---|---|---|---|
xx | 公有变量/方法 | ● | ● | ● | API的公有部分,提供外部调用 |
_xx | 保护变量/方法 | ● | ● | ☓ | API的非公有部分,不提供外部调用;但是能够被子类继承 |
__xx | 私有变量/方法 | ● | ☓ | ☓ | 私有成员,不提供外部调用;也不能被子类继承使用 |
__ xx__ | 系统定义变量/方法 | ☓ | ☓ | ☓ | 系统预先定义好的(通常业务程序中不需要调用到) |
2,代码举例
(1) _xx 和__xx的区别
>>> class A(object):
... def __method(self):
... print("i am a method in A")
... def _method2(self):
... print("i am a method in A2")
... def m1(self):
... self.__method()
... def m2(self):
... self._method2()
>>> class C(A):
... def m1(self):
... self.__method()
... def m2(self):
... self._method2()
>>> testc = C()
>>> testc.m1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in m1
AttributeError: 'C' object has no attribute '_C__method'
>>> testc.m2()
i am a method in A2
看上面的使用,
在testc的m1时候,调用对应的__method失败 (※__是不能被子类继承)
在testc的m2时候,调用对应的_method2成功 (※_是可以被子类继承)
查看C的名称,里面_method2从A继承过来了。__method是没有继承过来的。(只作为A的方法存在)
>>> dir(C)
['_A__method', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_method2', 'm1', 'm2']
(2) __ xx__ 通常是系统默认定义的名称
比如上面的 __ doc__, __ init__ 是不论定义什么类都需要有的名称和方法(类似于系统自留)
我的理解是通常业务上不需要显式调用,比如 __ init__是在 testc = C()的时候,代码执行时自动会调用__ init__进行类实例的初期化
而 xx, _xx, __xx 通常是代码者定义的业务方法或者变量(非系统自留)