Python的封装机制是把变量名字改掉,在类外还是可以访问的。下面例子的注释部分演示了如何在类外破坏封装性访问私有和保护变量,未注释部分则演示了保护变量和私有变量在子类调用的结果。
class A:
_弱私有变量 = None # protected
__强私有变量 = None # private
def __init__(self, a, b):
self._弱私有变量 = a
self.__强私有变量 = b
def _弱私有函数(self):
print("调用了_弱私有函数")
def __强私有函数(self):
print("调用了__强私有函数")
def show(self):
print("弱私有变量 = {0}".format(self._弱私有变量))
print("强私有变量 = {0}".format(self.__强私有变量))
class B(A):
def __init__(self):
super().__init__(1, 2)
def show(self):
print(self._弱私有变量) # protected 变量可访问
# print(self.__强私有变量) # A类的私有变量,不可访问
if __name__ == '__main__':
# a = A(100, 200)
# print("弱私有变量 = {0}".format(a._弱私有变量))
# print("强私有变量 = {0}".format(a._A__强私有变量))
# a._弱私有函数()
# a._A__强私有函数()
# a.show()
b = B()
b.show()