python学习笔记20(继承与多态)

继承与多态

继承:
在这里插入图片描述

单继承的实现: 只有一个父类

#创建父类
class Person(object):
    def __init__(self, name, age, money):
        self.name = name
        self.age = age
        self.__money = money

    def setMoney(self, money):
        self.__money = money
    def getMoney(self):
        return self.__money

    def run(self):
        print("run")

    def eat(self, food):
        print("eat " + food)
 
 #创建子项目       
class Student(Person):    #括号内写父类名
    def __init__(self, name, age, money, stuId):
        #调用父类中的__init__
        super(Student, self).__init__(name, age, money)
        # Person.__init__(self, name, age, money)    #person相当于super(Student, self)
        #子类可以有一些自己独有的属性
        self.stuId = stuId
    #父类中的方法直接全部继承,可定义子类中的方法
    def stuFunc(self):
        print(self.__money)

多继承的实现: 有几个父类

#创建一个父类
class Father(object):
    def __init__(self, money):
        self.money = money
    def play(self):
        print("play")
    def func(self):
        print("func1")

#创建另一个父类
class Mother(object):
    def __init__(self, faceValue):
        self.faceValue = faceValue
    def eat(self):
        print("eat")
    def func(self):
        print("func2")

class Child(Father, Mother):
    #定义子类的属性
    def __init__(self, money, faceValue):
        #写法
        Father.__init__(self, money)
        Mother.__init__(self, faceValue)
    #两个父类的方法全部自动继承

#定义main函数实例化子类
def main():
    c = Child(300, 100)
    print(c.money, c.faceValue)
    c.play()
    c.eat()
    #注意:父类中方法名相同,默认调用的是在括号中排前面的父类中的方法
    c.func()

#在直接执行此模块时运行main函数,调用时则不运行
if __name__ == "__main__":
    main()

多态: 一类事物有多种形态,如创建一个animal类,而cat、dog、mouse等都属于animal类(父类)下的一种形态(子类)
当需要创建animal类下的子类时,可以用继承的方法
当需要对若干animal下的子类做处理时,则需要用到多态的方法

示例:

#定义一个animal父类
class Animal(object):
    def __init__(self, name):
        self.name = name
    def eat(self):
        print(self.name + "吃")

#利用继承创建一个cat子类
class Cat(Animal):
    def __init__(self, name):
        super(Cat, self).__init__(name)

#利用继承创建一个mouse子类
class Mouse(Animal):
    def __init__(self, name):
        super(Mouse, self).__init__(name)

#创建一个独立的类,对animal进行交互
class Person(object):
    '''
    def feedCat(self, cat):
        print("给你食物")
        cat.eat()
    def feedMouse(self, mouse):
        print("给你食物")
        mouse.eat()
    '''
    #运用多态,给animal类下所有子类的实例化对象喂食
    def feedAnimal(self, ani):
        print("给你食物")
        ani.eat()

#实例化对象 
tom = Cat("tom")
jerry = Mouse("jerry")
per = Person()

#对象间交互
per.feedAnimal(tom)
per.feedAnimal(jerry)

猜你喜欢

转载自blog.csdn.net/weixin_42216171/article/details/85992457