1、在Python中要想定义的方法或者变量只在类内部使用不被外部调用,可以在方法和变量前面加 两个 下划线
#-*- coding:utf-8 -*- class A(object):
name = "sashuangyibing"
__mingzi = "bingyishuangsa" # 这个是私有变量,只能在类A之内可以使用,超过类A之外是无法引用到
def fun1(self):
print "This is common method"
def __fun2(self): # 这个是私有方法,只能在类A之内可以使用,超过类A之外是无法引用到
print "This is private method"
def fun4(self):
return self.__mingzi # 该私有变量在当前类之内可以被引用 class B(A):
def __init__(self):
super(B,self).__init__() def fun3(self):
print "fun3" aa = A()
print aa.name
print aa.fun4()
print aa._A__mingzi
aa._A__fun2()
输出:
sashuangyibing
bingyishuangsa
bingyishuangsa
This is private method
试错验证,如果按下面方法织造引用私有变量,会报没有该属性
aa = A()
print aa.__mingzi Traceback (most recent call last):
File "E:\04.script\work\test.py", line 21, in <module>
print aa.__mingzi
AttributeError: 'A' object has no attribute '__mingzi'
aa = A()
print aa.__fun2() Traceback (most recent call last):
File "E:\04.script\work\test.py", line 21, in <module>
print aa.__fun2()
AttributeError: 'A' object has no attribute '__fun2'
但是可以通过下面这种方法去引用私有变量和方法,在类名前面添加一个下划线
aa = A()
print aa._A__mingzi # A前面只有一个下线线
print aa._A__fun2() bingyishuangsa
This is private method