首页 > 编程语言 > 详细

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

时间:2014-03-04 03:53:38      阅读:482      评论:0      收藏:0      [点我收藏+]

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


bubuko.com,布布扣

Python - 继承(Inheritance) 的 详解 及 代码,布布扣,bubuko.com

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

原文:http://blog.csdn.net/caroline_wendy/article/details/20357767

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!