Chinaunix首页 | 论坛 | 博客
  • 博客访问: 382514
  • 博文数量: 112
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 800
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-29 13:41
文章分类

全部博文(112)

文章存档

2020年(1)

2018年(10)

2017年(27)

2016年(18)

2015年(31)

2014年(25)

分类: Python/Ruby

2017-07-21 17:13:02

  “封装(encapsulation)”是对对象(object)的一种抽象,将某些部分隐藏起来,在程序外部看不到,无法调用。

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. '''
  4. __tes 是私有方法,te方法和__tes方法在同一个类中,可以调用。
  5. '''
  6. class Test(object):
  7.     def __init__(self):
  8.         self.a = "a is here"
  9.         self.__b = "b is here"
  10.     def __tes(self):
  11.         print "func __tes is here"
  12.     def te(self):
  13.         print "func te is here"
  14.         self.__tes()
  15. if __name__ == "__main__":
  16.     c = Test()
  17.     print c.a
  18.     print c.te()
  19.     print c.__tes
  20.     

执行结果:

点击(此处)折叠或打开

  1. a is here
  2. func te is here
  3. func __tes is here
  4. None
  5. Traceback (most recent call last):
  6.   File "class5.py", line 16, in <module>
  7.     print c.__tes()
  8. AttributeError: 'Test' object has no attribute '__tes'
访问和修改私有字段;
property函数(只读)
@property可以将python定义的函数当做属性访问

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. '''
  4. 使用装饰器@property之后,在调用私有变量属性。
  5. '''
  6. class Test(object):
  7.     def __init__(self):
  8.         self.a = "i'm a"
  9.         self.__b ="i'm b"
  10. #使用属性方法将tes()方法变为一个类的静态属性。使之变为可读属性。    
  11.     @property
  12.     def tes(self):
  13.         return self.__b
  14. #使__b私有字段变成可写,只需调用tes属性并直接赋值即可(装饰器格式为‘@函数名.setter’)   
  15.     @tes.setter
  16.     def tes(self,value):
  17.         self.__b = value

  18. if __name__ == "__main__":
  19.     c = Test()
  20.     print c.tes
  21.     print '------'
  22.     c.tes = "i'm already not b"
  23.     print c.tes
执行结果:

点击(此处)折叠或打开

  1. i'm b
  2. ------
  3. i'm already not b




阅读(680) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~