循环两次,实现从键盘输入序号,输入1选择创建狗对象,进而输入狗的名字和颜色,调用intr方法,eat方法,从键盘输入序号,输入2选择创建猫对象,进而输入猫的名字和品种,调用intr方法,eat方法
时间: 2024-02-28 18:57:00 浏览: 52
好的,我理解了你的要求。下面是实现这个功能的Python代码:
```python
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def intr(self):
print(f"I am a {self.color} dog named {self.name}.")
def eat(self):
print(f"{self.name} is eating.")
class Cat:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def intr(self):
print(f"I am a {self.breed} cat named {self.name}.")
def eat(self):
print(f"{self.name} is eating.")
for i in range(2):
choice = input("Enter 1 to create a dog or 2 to create a cat: ")
if choice == "1":
name = input("Enter the dog's name: ")
color = input("Enter the dog's color: ")
dog = Dog(name, color)
dog.intr()
dog.eat()
elif choice == "2":
name = input("Enter the cat's name: ")
breed = input("Enter the cat's breed: ")
cat = Cat(name, breed)
cat.intr()
cat.eat()
else:
print("Invalid choice. Please enter 1 or 2.")
```
你可以将这段代码复制到一个Python文件中,然后运行它,就可以进行测试了。注意,这里只循环了两次,如果你想循环更多次,可以将循环次数改成你想要的数值。
阅读全文