酷代码 AI
菜单
服务商

Python编程:从Animal类扩展到Cat类,实现各类方法及对象调用

1. 在animal类中增加一个方法talk,输出i can speak。 ```python class Animal: def __init__(self, name, kind): self.name = name self.kind = kind def talk(self): print("I can speak.") ``` 2. 在刚才的animal类中增加一个方法myprint,输出name和kind的值。 ```python class Animal: def __init__(self, name, kind): self.name = name self.kind = kind def talk(self): print("I can speak.") def myprint(self): print("Name:", self.name) print("Kind:", self.kind) ``` 3. 定义一个类cat,定义私有属性food和enemy,在构造函数中赋值,继承自animal。 ```python class Cat(Animal): def __init__(self, name, kind, food, enemy): super().__init__(name, kind) self.__food = food self.__enemy = enemy ``` 4. 定义talk方法,输出喵喵。 ```python class Cat(Animal): def __init__(self, name, kind, food, enemy): super().__init__(name, kind) self.__food = food self.__enemy = enemy def talk(self): print("喵喵") ``` 5. 定义print方法输出food和enemy。 ```python class Cat(Animal): def __init__(self, name, kind, food, enemy): super().__init__(name, kind) self.__food = food self.__enemy = enemy def talk(self): print("喵喵") def print_food_and_enemy(self): print("Food:", self.__food) print("Enemy:", self.__enemy) ``` 6. 定义方法catchmouse,输出i catch a mouse. ```python class Cat(Animal): def __init__(self, name, kind, food, enemy): super().__init__(name, kind) self.__food = food self.__enemy = enemy def talk(self): print("喵喵") def print_food_and_enemy(self): print("Food:", self.__food) print("Enemy:", self.__enemy) def catch_mouse(self): print("I catch a mouse.") ``` 7. 定义方法myprint,输出子类对象所有属性。 ```python class Cat(Animal): def __init__(self, name, kind, food, enemy): super().__init__(name, kind) self.__food = food self.__enemy = enemy def talk(self): print("喵喵") def print_food_and_enemy(self): print("Food:", self.__food) print("Enemy:", self.__enemy) def catch_mouse(self): print("I catch a mouse.") def myprint(self): print("Name:", self.name) print("Kind:", self.kind) print("Food:", self.__food) print("Enemy:", self.__enemy) ``` 8. 定义animal类对象a2,(octopus,fish)。 ```python a2 = Animal("Octopus", "Fish") ``` 9. 分别调用方法talk和myprint。 ```python a2.talk() a2.myprint() ``` 10. 定义cat类对象c1,--cat,feline,[fish,meat,milk,icecream],[老鹰,豹子]。 ```python c1 = Cat("Cat", "Feline", ["fish", "meat", "milk", "icecream"], ["老鹰", "豹子"]) ``` 11. 用c1依次调用类中所有方法。 ```python c1.talk() c1.print_food_and_enemy() c1.catch_mouse() c1.myprint() ``` ######[AI写代码神器 | 1028点数解答 | 2024-06-13 18:11:31]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]