#-*- encoding:UTF-8 -*- class Demo1 : classAttrA = "类属性, 公有属性, 静态属性 ---> classAttrA" __classAttrB = "类的私有属性 ---> __classAttrB" def getClassAttrB(self): return Demo1.__classAttrB def getClassAttrB_2(self): return self.__classAttrB if __name__ == '__main__': # 类的公有属性可以通过类名访问, 而类私有属性不可以 print Demo1.classAttrA try : print Demo1.__classAttrB except AttributeError, msg: print msg # 类的私有属性 只能在类范围内进行读/写 instance = Demo1() print instance.getClassAttrB() print instance.getClassAttrB_2()
对象的公有属性可以通过对象名访问, 而对象私有属性不可以
#-*- encoding:UTF-8 -*- class Demo2 : def initAttrs(self): self.instanceAttrA = "对象的公有属性 ---> instanceAttrA" self.__instanceAttrB = "对象的私有属性 ---> instanceAttrB" def displayAttrs(self): print self.instanceAttrA print self.__instanceAttrB def setAttrA(self,attrA): self.instanceAttrA = attrA def setAttrB(self,attrB): self.__instanceAttrB = attrB if __name__ == '__main__': # 对象的公有属性, 可以通过对象名来访问, 对象的私有属性不可以 instanceA = Demo2() instanceB = Demo2() instanceA.initAttrs() instanceB.initAttrs() print instanceA.instanceAttrA try : print instanceA.instanceAttrB except AttributeError, msg : print msg print "#" * 50 instanceA.displayAttrs() instanceA.setAttrA("instanceA set attrA") instanceA.setAttrB("instanceB set attrB") print "#"*20, "instanceA", "#"*20 instanceA.displayAttrs() print "#"*20, "instanceB", "#"*20 instanceB.displayAttrs()