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

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


继承可以使代码重用, 是类型和子类型的关系;

Python中, 继承是在类名的括号中填入继承的基类, 即class DerivedClass(BaseClass):

基类初始化需要使用self变量, 即BaseClass.__init__(self, val1, val2), 需要手动调用基类的构造函数;

派生共享基类的成员变量, 可以直接使用self.val进行使用;

可以重写(override)基类的方法, 则使用时, 会优先调用派生类的方法;


代码如下:

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"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值