博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python——面向对象的三大特性:封装,继承,多态
阅读量:3922 次
发布时间:2019-05-23

本文共 4904 字,大约阅读时间需要 16 分钟。

一、封装:

  • 面向对象第一步 : 将属性和方法封装到一个抽象的类中
  • 外界使用类创建对象,然后让对象调用方法
  • 对象方法的细节都封装在类的内部
  • 例题:

需求

1.小明体重75.0公斤
2.小明每次跑步会减肥0.5公斤
3.小明每次吃东西会增重1攻击

需求

1.小明和小美都爱跑步
2.小美体重45.0公斤
3.小明体重75.0公斤
4.每次跑步会减肥0.5公斤
5.每次吃东西会增重1攻击

class Person():    def __init__(self,name,weight):        self.name = name        self.weight = weight    def __str__(self):        return '我的名字叫%s 体重是%.2f' %(self.name,self.weight)    def run(self):        print('%s爱跑步' %self.name)        self.weight -= 0.5    def eat(self):        print('%s吃东西' %self.name)        self.weight += 1xiaoming = Person('小明',76.0)print(xiaoming)xiaoming.run()print(xiaoming)xiaoming.eat()print(xiaoming)结果:我的名字叫小明 体重是76.00小明爱跑步我的名字叫小明 体重是75.50小明吃东西我的名字叫小明 体重是76.50
  • 练习题2:

需求:

1.房子有户型,总面积和家具名称列表
新房子没有任何的家具

2.家具有名字和占地面积,其中

床:占4平米
衣柜:占2平面
餐桌:占1.5平米
3.将以上三件家具添加到房子中
4.打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表

##定义家具类:房子类要使用家具,则被使用的类应先开发class HouseItem():    def __init__(self,name,area):        self.name = name        self.area = area    def __str__(self):        return '[%s]占地 %.2f' %(self.name,self.area)#1.创建家具# bed = HouseItem('bed',4)# print(bed)# table = HouseItem('table',2)# print(table)##定义房子类class House():    def __init__(self,house_type,area):        self.house_type = house_type        self.area = area        #剩余面积        self.free_area = area    ##剩余面积的初始值为总面积        self.item_list = []    def __str__(self):        return ('户型:%s\n总面积:%.2f[剩余:%.2f]\n家具:%s'                %(self.house_type,self.area,self.free_area,self.item_list))    def add_item(self,item):        #1.判断家具的面积        if item.area > self.free_area:            print('%s的面积太大,无法添加' %item.name)        #2.将家具的名称添加到列表中        self.item_list.append(item.name)        #3.计算剩余面积        self.free_area -= item.area#1.创建家具对象bed = HouseItem('bed',4)# print(bed)chest = HouseItem('chest',2)# print(yg)table = HouseItem('table',1.5)# print(table)#2.创建房子对象my_house = House('两室一厅',100)#3.添加家具my_house.add_item(bed)my_house.add_item(chest)my_house.add_item(table)print(my_house)结果:户型:两室一厅总面积:100.00[剩余:92.50]家具:['bed', 'chest', 'table']
  • 练习题3:
1.士兵瑞恩有一把AK472.士兵可以开火(士兵开火扣动的是扳机)3.枪 能够 发射子弹(把子弹发射出去)4.枪 能够 装填子弹 --增加子弹的数量Soldier                     Gun-------------               -----------------name                        modelgun                         bullet_count #子弹数量足够多才能完成射击的动作-------------               -----------------__init__(self):                 __init__(self):fire(self):                 add_bullet(self,count):#装填子弹的方法shoot(self):
##创建枪类class Gun():    def __init__(self,model):        self.model = model        self.bullet_count = 0     ##子弹的数量一开始为0    def add_bullet(self,count):        self.bullet_count += count    def shoot(self):        if self.bullet_count <=0:            print('%s没有子弹了...' %self.model)        self.bullet_count -= 1        print('%s~~~~~%s' %(self.model,self.bullet_count))##定义士兵类class Soldier():    def __init__(self,name):        self.name = name        self.gun = None    def fire(self):        if self.gun == None:            print('%s还没有枪...' %self.name)        self.gun.add_bullet(10)        self.gun.shoot()##定义枪对象ak47 = Gun('ak47')ak47.add_bullet(50)ak47.shoot()##定义士兵对象ryan = Soldier('Ryan')ryan.gun = ak47ryan.fire()结果:ak47~~~~~49ak47~~~~~58

二、继承:

  • 继承:实现代码的重用,相同的代码不需要重复写
  • 子类继承自父类,可以直接享受父类中已经封装好的方法
  • 子类重应该根据职责,封装子类特有的属性和方法
class Animal():    def eat(self):        print('吃~~~~~')    def drink(self):        print('喝')    def run(self):        print('跑')    def sleep(self):        print('睡')class Cat(Animal):    def call(self):        print('喵~')fentiao = Cat()fentiao.eat()fentiao.run()fentiao.call()结果:吃~~~~~跑喵~
  • 子类可以继承父类的所有属性和方法
  • 继承具有传递性,子类拥有父类的父类的属性和方法
class Animal():    def eat(self):        print('吃~~~~~')    def drink(self):        print('喝')    def run(self):        print('跑')    def sleep(self):        print('睡')class Cat(Animal):    def call(self):        print('喵~')class HelloKitty(Cat):    def speak(self):        print('我能说英语')class Dog(Animal):    def bark(self):        print('汪~')kt = HelloKitty()kt.eat()kt.speak()结果:吃~~~~~我能说英语
  • 如果子类重写了父类的方法
  • 在运行中,只会调用在子类中重写的方法而不会调用父类方法
class Cat():    def call(self):        print('喵~')class HelloKitty(Cat):    def speak(self):        print('我能说英语')    def call(self):        print('@#@$@$@#@!#')kt = HelloKitty()kt.call()结果:@#@$@$@#@!#
  • 如果子类重写父类的方法后,还想调用父类的方法:
class Cat():    def call(self):        print('喵~')class HelloKitty(Cat):    def speak(self):        print('我能说英语')    def call(self):        #1.针对子类特有的需求,编写代码        print('@#@$@$@#@!#')        #2.调用原本在父类中封装的方法        # Cat.call(self)    ##两种方法选一种        super().call()kt = HelloKitty()kt.call()结果:@#@$@$@#@!#喵~
  • 多继承:子类拥有多个父类叫多继承,拥有所有父类的属性和方法
class A():    def test(self):        print('A---->test方法')    def demo(self):        print('A---->demo方法')class B():    def test(self):        print('B---->test方法')    def demo(self):        print('B---->demo方法')class C(A,B):    ##当父类的方法或属性同名时,按括号中的父类先后顺序执行    passc = C()c.test()c.demo()结果:A---->test方法A---->demo方法

转载地址:http://erhrn.baihongyu.com/

你可能感兴趣的文章
Leetcode 111. 二叉树的最小深度
查看>>
Leetcode 226. 翻转二叉树
查看>>
Leetcode 617. 合并二叉树
查看>>
Leetcode 654. 最大二叉树
查看>>
Leetcode 304. 二维区域和检索 - 矩阵不可变
查看>>
Leetcode 56. 合并区间
查看>>
Leetcode 57. 插入区间
查看>>
Leetcode 58. 最后一个单词的长度
查看>>
Leetcode 61. 旋转链表
查看>>
Leetcode 66. 加一
查看>>
Leetcode 73. 矩阵置零
查看>>
Leetcode 60. 排列序列
查看>>
Leetcode 77. 组合
查看>>
Leetcode 74. 搜索二维矩阵
查看>>
Leetcode 86. 分隔链表
查看>>
Leetcode 92. 反转链表 II
查看>>
Leetcode 88. 合并两个有序数组
查看>>
Leetcode 89. 格雷编码
查看>>
Leetcode 67. 二进制求和
查看>>
Leetcode 69. x 的平方根
查看>>