python学习总结之类对象

10 篇文章 0 订阅

面向对象(OO)是一种编程的思想而不是一种语言,python是用C语言来现实的面向对象的语言,面向对象的目的就是代码的重用,减少重复性的开发,面向对象的代码重用机制包括封装、继承、多态。面向对象的核心则是抽象、分离接口和实现。

这里让我们来一起探讨一下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







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值