python-class(5),, 1 #!/usr/


 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_methods21 ‘‘‘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 += 136         self.publicCount += 137         print self.__secretCount38         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.publicCount49 #print counter.__secretCount  # AttributeError: JustCounter instance has no attribute ‘__secretCount‘50 print counter._JustCounter__secretCount #Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性

python-class(5)

评论关闭