[python] 私有变量和私有方法

1、在Python中要想定义的方法或者变量只在类内部使用不被外部调用,可以在方法和变量前面加 两个 下划线

 

 1 #-*-  coding:utf-8 -*-
 2 
 3 class A(object):
 4     name = "sashuangyibing"
 5     __mingzi = "bingyishuangsa"    # 这个是私有变量,只能在类A之内可以使用,超过类A之外是无法引用到
 6     def fun1(self):
 7         print "This is common method"
 8     def __fun2(self):   # 这个是私有方法,只能在类A之内可以使用,超过类A之外是无法引用到
 9         print "This is private method"
10     def fun4(self):
11         return self.__mingzi    # 该私有变量在当前类之内可以被引用
12 
13 class B(A):
14     def __init__(self):
15         super(B,self).__init__()
16     
17     def fun3(self):
18         print "fun3"
19         
20 aa = A()
21 print aa.name
22 print aa.fun4()
23 print aa._A__mingzi
24 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

  

 

posted @ 2018-08-28 15:06  iSZ  阅读(306)  评论(0编辑  收藏  举报