Python基础35-面向对象(综合案例:封装/继承/多态)

2018-06-06  本文已影响29人  Jacob_LJ

Python基础-面向对象

面向对象案例:封装、继承、多态

1 需求

定义三个类, 小狗, 小猫, 人

小狗: 姓名, 年龄(默认1岁);        吃饭, 玩, 睡觉, 看家(格式: 名字是xx, 年龄xx岁的小狗在xx)

小猫: 姓名, 年龄(默认1岁);        吃饭, 玩, 睡觉, 捉老鼠(格式: 名字是xx, 年龄xx岁的小猫在xx)

人:   姓名, 年龄(默认1岁), 宠物;  吃饭, 玩, 睡觉(格式: 名字是xx, 年龄xx岁的人在xx)
                                养宠物(让所有的宠物吃饭, 玩, 睡觉),
                                让宠物工作(让所有的宠物根据自己的职责开始工作)

2 思考点

封装

继承

多态

可进一步优化点

class Animal:

    def __init__(self, name, age=1):
        self.name =  name
        self.age = age

    def eat(self):
        print("%s,在吃饭" % self)

    def play(self):
        print("%s,在玩" % self)

    def sleep(self):
        print("%s,在睡觉" % self)



class Person(Animal):

    def __init__(self, name, pets, age):
        super().__init__(name, age)
        self.pets = pets

    def yang_pets(self):
        for pet in self.pets:
            pet.eat()
            pet.play()
            pet.sleep()

    def make_pets_word(self):
        for pet in self.pets:
            pet.work()

    def __str__(self):
        return "名字叫{},年龄是{}的人".format(self.name, self.age)

class Dog(Animal):

    def work(self):
        print("小狗在看家")

    def __str__(self):
        return "名字叫{},年龄是{}的小狗".format(self.name, self.age)


class Cat(Animal):
    def work(self):
        print("小猫在抓老鼠")

    def __str__(self):
        return "名字叫{},年龄是{}的小猫".format(self.name, self.age)

d = Dog("小Dog", 3)
c = Cat("小Cat", 4)
p = Person("JJ",[d, c], 20)

p.eat()
p.play()
p.sleep()
p.yang_pets()
p.make_pets_word()

>>>>打印结果
名字叫JJ,年龄是20的人,在吃饭
名字叫JJ,年龄是20的人,在玩
名字叫JJ,年龄是20的人,在睡觉
名字叫小Dog,年龄是3的小狗,在吃饭
名字叫小Dog,年龄是3的小狗,在玩
名字叫小Dog,年龄是3的小狗,在睡觉
名字叫小Cat,年龄是4的小猫,在吃饭
名字叫小Cat,年龄是4的小猫,在玩
名字叫小Cat,年龄是4的小猫,在睡觉
小狗在看家
小猫在抓老鼠
上一篇 下一篇

猜你喜欢

热点阅读