Python不像C++、Java、C#等有明确的公共、私有或受保护的关键字来定义成员函数或属性,它使用约定的单下划线“_"和"__"双下划线作为函数或属性的前缀来标识。使用单下划线还是双下划线,是有很大的区别的。
1. 单下划线的函数或属性,在类定义中可以调用和访问,类的实例可以直接访问,子类中可以访问;
2. 双下划线的函数或属性,在类定义中可以调用和访问,类的实例不可以直接访问,子类不可访问。
注意:对于双下划线的函数或属性,Python解释器使用了名字混淆的方法, 将私有的方法"__method"变成了"_classname__method"了,具体看下文示例。
class Base(object):
def __private(self):
print("private value in Base")
def _protected(self):
print("protected value in Base")
def public(self):
print("public value in Base")
self.__private()
self._protected()
class Derived(Base):
def __private(self):
print("override private")
def _protected(self):
print("override protected")
print dir(Base)
print("="*80)
d = Derived()
d.public()
d._protected()
d._Derived__private()
print("="*80)
d.__private()
输出结果如下:
>>>
['_Base__private', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_protected', 'public']
================================================================================
public value in Base
private value in Base
override protected
override protected
override private
================================================================================
Traceback (most recent call last):
File "D:\temp\test.py", line 91, in <module>
d.__private()
AttributeError: 'Derived' object has no attribute '__private'
>>>
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/thomashtq/article/details/46817591