Chinaunix首页 | 论坛 | 博客
  • 博客访问: 749969
  • 博文数量: 231
  • 博客积分: 3217
  • 博客等级: 中校
  • 技术积分: 2053
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-04 12:01
文章分类

全部博文(231)

文章存档

2015年(1)

2013年(10)

2012年(92)

2011年(128)

分类: LINUX

2012-06-05 15:31:11

面向对象程序设计中对象(object)基本上可以看做数据以及一系列可以存取。操作这些数据的方法所组成的集合。
多态:意味着可以对不同类的对象使用相同的操作,它们会像被施了魔法一样工作。
封装:对外部世界隐藏对象的工作细节。
继承:以普通的类为基础建立专门的类对象。
类就是一种对象,所有的对象都属于某一个类,称为类的实例(instance)
当一个对象所属的类是另外一个对象所属类的子集时,前者是后者的子类,后者是前者的超类。
百灵鸟是鸟类的子类,鸟类是百灵鸟的超类。
创建自己的类:

点击(此处)折叠或打开

  1. >>> __metaclass__=type
  2. >>> class Per:
  3.     def setName(self,name):
  4.         self.name=name
  5.     def getName(self):
  6.         return self.name
  7.     def greet(self):
  8.         print 'hello world'

  9.         
  10. >>> f=Per()
  11. >>> f.setName('longpengcheng')
  12. >>> f.greet()
  13. hello world
  14. >>> f.getName()
  15. 'longpengcheng'
  16. >>>
新式类的语法中,需要在模块或者脚本开始的步骤地方放置赋值语句__metaclass__=type,使用class创建Per类,class语句会在函数定义的地方创建创建自己的命令空间。self是对像自身的引用。
为了让方法或者特性变为私有(从外部无法访问),只要在它的名字前面加上双下划线即可:

点击(此处)折叠或打开

  1. >>> __metaclass__=type
  2. >>>
  3. KeyboardInterrupt
  4. >>> __metaclass__=type
  5. >>> class Sec:
  6.     def __in(self):
  7.         print 'hello world'
  8.     def ac(self):
  9.         print 'long'

  10.         
  11. >>> d=Sec()
  12. >>> d.__in()

  13. Traceback (most recent call last):
  14.   File "", line 1, in <module>
  15.     d.__in()
  16. AttributeError: 'Sec' object has no attribute '__in'
  17. >>> d.ac()
  18. long


阅读(908) | 评论(0) | 转发(0) |
0

上一篇:函数

下一篇:scons

给主人留下些什么吧!~~