继承(Inheritance) 的 详解 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/20357767
继承可以使代码重用, 是类型和子类型的关系;
Python中, 继承是在类名的括号中填入继承的基类, 即class DerivedClass(BaseClass):
基类初始化需要使用self变量, 即BaseClass.__init__(self, val1, val2), 需要手动调用基类的构造函数;
派生共享基类的成员变量, 可以直接使用self.val进行使用;
可以重写(override)基类的方法, 则使用时, 会优先调用派生类的方法;
代码如下:
# -*- coding: utf-8 -*- #==================== #File: ClassExercise.py #Author: Wendy #Date: 2014-03-03 #==================== #eclipse pydev, python2.7 class Person: def __init__(self, name, age): self.name = name self.age = age print(‘(Initialized Person: {0})‘.format(self.name)) def tell(self): print(‘Name:"{0}" Age:"{1}"‘.format(self.name, self.age)) class Man(Person): #继承 def __init__(self, name, age, salary): Person.__init__(self, name, age) self.salary = salary print(‘(Initialized Man: {0})‘.format(self.name)) def tell(self): #重写基类方法 Person.tell(self) print(‘Salary: "{0:d}"‘.format(self.salary)) class Woman (Person): def __init__(self, name, age, score): Person.__init__(self, name, age) self.score = score print(‘(Initialized Woman: {0})‘.format(self.name)) def tell(self): #重写基类方法 Person.tell(self) print(‘score: "{0:d}"‘.format(self.score)) c = Woman(‘Caroline‘, 30, 80) s = Man(‘Spike‘, 25, 15000) print(‘\n‘) members = [c, s] for m in members: m.tell()
输出:
(Initialized Person: Caroline) (Initialized Woman: Caroline) (Initialized Person: Spike) (Initialized Man: Spike) Name:"Caroline" Age:"30" score: "80" Name:"Spike" Age:"25" Salary: "15000"