python-class(5)

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 ############################
 4 #File Name: class5.py
 5 #Author: frank
 6 #Email: frank0903@aliyun.com
 7 #Created Time:2017-09-04 17:22:45
 8 ############################
 9 
10 '''
11 类属性与方法
12 
13 类的私有属性
14     __private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
15 
16 类的方法
17     在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数
18 
19 类的私有方法
20     __private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods
21 '''
22 
23 '''
24 单下划线、双下划线、头尾双下划线说明:
25 __foo__: 定义的是特列方法,类似 __init__() 之类的。
26 _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
27 __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
28 '''
29 
30 class JustCounter:
31     __secretCount = 0  # 私有变量
32     publicCount = 0    # 公开变量
33 
34     def count(self):
35         self.__secretCount += 1
36         self.publicCount += 1
37         print self.__secretCount
38         self.__myMth()
39 
40     def __myMth(self):
41         print "private method"
42 
43 
44 counter = JustCounter()
45 counter.count()
46 counter.count()
47 #counter.__myMth()  #AttributeError: JustCounter instance has no attribute '__myMth'
48 print counter.publicCount
49 #print counter.__secretCount  # AttributeError: JustCounter instance has no attribute '__secretCount'
50 print counter._JustCounter__secretCount #Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性
原文地址:https://www.cnblogs.com/black-mamba/p/7476809.html