【1】
class A(object):
def __init__(self):
self.__data=[] #翻译成 self._A__data=[]
def add(self,item):
self.__data.append(item) #翻译成 self._A__data.append(item)
def printData(self):
print self.__data #翻译成 self._A__data
a=A()
a.add('hello')
a.add('python')
a.printData()
#print a.__data #外界不能访问私有变量 AttributeError: 'A' object has no attribute '__data'
print a._A__data #通过这种方式,在外面也能够访问“私有”变量;这一点在调试中是比较有用的!
运行结果是:
class A():
def __init__(self):
self.__name='python' #私有变量,翻译成 self._A__name='python'
def __say(self): #私有方法,翻译成 def _A__say(self)
print self.__name #翻译成 self._A__name
a=A()
#print a.__name #访问私有属性,报错!AttributeError: A instance has no attribute '__name'
print a.__dict__ #查询出实例a的属性的集合
print a._A__name #这样,就可以访问私有变量了
#a.__say()#调用私有方法,报错。AttributeError: A instance has no attribute '__say'
print dir(a)#获取实例的所有属性和方法
a._A__say() #这样,就可以调用私有方法了
运行结果:
【3】小漏洞:派生类和基类取相同的名字就可以使用基类的私有变量
class A():
def __init__(self):
self.__name='python' #翻译成self._A__name='python'
class B(A):
def func(self):
print self.__name #翻译成print self._B__name
instance=B()
#instance.func()#报错:AttributeError: B instance has no attribute '_B__name'
print instance.__dict__
print instance._A__name
运行结果:
class A():
def __init__(self):
self.__name='python' #翻译成self._A__name='python'
class A(A): #派生类和基类取相同的名字就可以使用基类的私有变量。
def func(self):
print self.__name #翻译成print self._A__name
instance=A()
instance.func()
运行结果:
(完)