Python - 继承(Inheritance) 详解 及 代码
2014-03-03 09:42
597 查看
继承(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"
相关文章推荐
- Python - 继承(Inheritance) 详解 及 代码
- Python - 继承(Inheritance) 的 详解 及 代码
- Python面向对象之继承代码详解
- Python类的继承和多态代码详解
- python中的常量和变量代码详解
- python数字图像处理之高级滤波代码详解
- [python]WindowsError的错误代码详解
- python绘制条形图方法代码详解
- 详解字典树Trie结构及其Python代码实现
- Python练习代码 -- 类, 继承
- Python代码格式化工具YAPF详解
- Python 代码调试技巧(图文详解)
- [python]WindowsError的错误代码详解
- Python - 字典(dict) 详解 及 代码
- Python - 序列(sequence) 详解 及 代码
- 代码的坏味道之十一 :Parallel Inheritance Hierarchies(平行继承体系)
- 基于Python代码编辑器的选用(详解)
- 详解如何利用Cython为Python代码加速
- Python之自动生成代码继承关系
- Python&OpenCV - 读写(read&write)视频(video) 详解 及 代码