python学习总结之类对象
面向对象(OO)是一种编程的思想而不是一种语言,python是用C语言来现实的面向对象的语言,面向对象的目的就是代码的重用,减少重复性的开发,面向对象的代码重用机制包括封装、继承、多态。面向对象的核心则是抽象、分离接口和实现。
这里让我们来一起探讨一下python的面向对象的具体格式和方法:
首先是self参数变量,它是区别方法和一般函数的一个标识,类方法必须含有这个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方法
类的参数变量和对象的参数变量:
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方法
'''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学习总结之类对象 的全部内容, 来源链接: utcz.com/z/388446.html