您的位置:首页 > 编程语言 > Python开发

Python - 继承(Inheritance) 的 详解 及 代码

2014-03-03 09:42 615 查看

继承(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"




本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387934
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: