python学习总结之类对象
2012-06-28 14:43
489 查看
面向对象(OO)是一种编程的思想而不是一种语言,python是用C语言来现实的面向对象的语言,面向对象的目的就是代码的重用,减少重复性的开发,面向对象的代码重用机制包括封装、继承、多态。面向对象的核心则是抽象、分离接口和实现。
这里让我们来一起探讨一下python的面向对象的具体格式和方法:
首先是self参数变量,它是区别方法和一般函数的一个标识,类方法必须含有这个self的变量:
类的参数变量和对象的参数变量:
这里让我们来一起探讨一下python的面向对象的具体格式和方法:
首先是self参数变量,它是区别方法和一般函数的一个标识,类方法必须含有这个self的变量:
#修改了sayhi()方法,将self去掉后:就会出现错误,说是没有参数。 def sayHi(): print 'hello,how are you?', self.name [root@fsailing1 class]# py method.py Traceback (most recent call last): File "method.py", line 9, in ? p.sayHi() TypeError: sayHi() takes no arguments (1 given)init和del方法,这两个方法是在类对象被实例化话的时候就已经被初始化了,或者类对象被回收之后自动出发del方法
类的参数变量和对象的参数变量:
class Person: population=0 def __init__(self,name): self.name=name Person.population+=1 print '(Initializing %s)' %self.name def __def__(self): print '%s says bye.' %self.name Person.population-=1 if Person.population==0: print 'I am the last one.' else: print 'there are still %d people left' %Person.population def sayhi(self): print 'hi,my name is %s' %self.name def howMany(self): if Person.population==1: print 'I am the only person here.' else: print 'We have %d persons here.' %Person.population继承,注意书写的格式,这里的的子类覆盖了父类的init方法和tell方法
class SchoolMember: '''Represents any school member.''' def __init__(self,name,age): self.name=name self.age=age print '(Initialized schoolMember: %s)' %self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' %(self.name,self.age) class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age) self.salary=salary print '(Initialized Teacher: %s)' %self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' %self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age) self.marks=marks print '(Initialized Student :%s)' %self.name def tell(self): SchoolMember.tell(self) print 'Marks is :"%d"' %self.marks
相关文章推荐
- python学习总结之类对象
- Java学习总结之类与对象
- Python学习笔记总结(一)对象和流程语句总结
- python学习总结三(python对象)
- 第三周python面向对象学习总结
- Python学习总结,python入门,python创建对象
- Python学习笔记之类和对象
- python基础学习总结2——类与对象
- python学习总结(面向对象进阶)
- Python学习教程(七)——抽象之类和对象
- Python对象类型总结(学习记录)
- Python学习笔记总结(一)对象和流程语句总结
- Python快速学习10: 循环的对象及设计 (生活的规律)
- 深度学习物体检测(九)——对象检测YOLO系列总结
- Python学习问题和薄弱点总结
- python学习习题总结(1)——求数字位数,正序倒序输出
- python学习_应用pickle模块封装和拆封数据对象
- Python学习笔记--类和对象
- Python模块学习 ---- pickle, cPickle 对象序列化/反序列化
- Entity Framework 学习总结之十:加载相关对象