首页 > 代码库 > 简明python教程七----面向对象的编程(下)

简明python教程七----面向对象的编程(下)

继承:类之间的类型和子类型关系

代码重用:SchoolMember类被称为 基本类或超类,而Teacher和Student类被称为导出类或者子类

#!/usr/bin/python
#Filename:Inherit.py

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:"%d"%self.marks


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

print #prints a blank line

members = [t,s]
for member in members:
    member.tell()

结果:

(Initialized SchoolMember:Mrs.Shrividya)
(Initialized Teacher:Mrs.Shrividya)
(Initialized SchoolMember:Swaroop)
(Initialized Student:Swaroop)

Name:"Mrs.Shrividya" Age:"40"
Salary: "30000"
Name:"Swaroop" Age:"22"
Marks:"75"

注意:为了使用继承,把基本类的名称作为一个元组跟在定义类时的类名称之后。

基本类的__init__方法专门使用self变量调用,这样我们就可以初始化对象的基本类部分。

记住:python不会自动调用基本类的constructor,需要亲自专门调用它。

 

简明python教程七----面向对象的编程(下)