流星

流星飞过的刹那,我....
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python的面向对象编程

Posted on 2009-02-20 09:23  泥土  阅读(329)  评论(0编辑  收藏  举报

     在python中,类和对象是面向对象的两个主要方面。这里的类是创建一个新类型,而对象可以看作是类的一个实例。

     对象可以使用普通的属于对象的变量存储数据。属于一个对象或类的变量被称为。对象也可以使用属于类的函数来具有功能,这样的函数被称为类的方法。域和方法可以合称为类的属性。

     域有两种类型--属于每个实例(对象)的方法称为实例变量;属于类本身的称为类变量。

self:

     类的方法和普通的函数只有一个特别的区别--他们必须有一个额外的第一个参数名称,但是在调用方法的时候你不为这个参数赋值,python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称为self

 

__init__方法:

     __init__方法在类的一个对象被建立时,马上运行,这个方法可以用来对你的对象做一些你希望的初始化。注意,这个名称的开始和结尾都是双下划线。

 

类与对象的方法:

可以看一个例子来理解:

class Person:
    population=0
    def __init__(self,name):
        self.name=name
        Person.population+=1
    def __del__(self):
        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)
            
s=Person("jlsme")
s.sayHi()
s.howMany()

k=Person("kalam")
k.sayHi()
k.howMany()

s.sayHi()
s.howMany()
输出:
hi my name is jlsme
i am the only person here
hi my name is kalam
we have 2 persons here.
hi my name is jlsme
we have 2 persons here.

population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。

观察可以发现__init__方法用一个名字来初始化Person实例。在这个方法中,我们让population增加1,这是因为我们增加了一个人。同样可以发现,self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。

记住,你能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考

 

继承:

     可以使用继承来实现代码的重用.

class SchoolMember:
    '''Represents any school member.'''
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def tell(self):
        '''Tell my details.'''
        print('Name:"%s" Age:"%s"'%(self.name,self.age),end=" ")
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 Teacher:%s)"%self.name)
    def tell(self):
        SchoolMember.tell(self)
        print('Marks:"%d"'%self.marks)

t=Teacher("Mrs. Shrividya",40,30000)
s=Student("jlsme",22,75)

members=[t,s]
for member in members:
	member.tell()
    
输出:
(Initialized Teacher:Mrs. Shrividya)
(Initialized Teacher:jlsme)
Name:"Mrs. Shrividya" Age:"40" Salary:"30000"
Name:"jlsme" Age:"22" Marks:"75"