私有变量和私有方法

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:4.scriptworktest.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:4.scriptworktest.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

  

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注