This repository was archived by the owner on Jun 4, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo1_inheritance.py
More file actions
65 lines (48 loc) · 1.61 KB
/
demo1_inheritance.py
File metadata and controls
65 lines (48 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
demo1: 类继承 (Inheritance)
场景:动物分类系统
"""
from datetime import datetime
class Animal:
"""基类"""
def __init__(self, name: str, age: int):
self.name = name
self.age = age
self._created_at = datetime.now()
def eat(self) -> str:
return f"{self.name} 正在吃东西"
def sleep(self) -> str:
return f"{self.name} 正在睡觉"
def get_info(self) -> str:
return f"动物名: {self.name}, 年龄: {self.age}岁"
class Dog(Animal):
def __init__(self, name: str, age: int, breed: str):
super().__init__(name, age)
self.breed = breed
def bark(self) -> str:
return f"{self.name} 汪汪叫! 🐶"
def get_info(self) -> str:
return f"{super().get_info()}, 品种: {self.breed}, 类型: 狗"
class Cat(Animal):
def __init__(self, name: str, age: int, color: str):
super().__init__(name, age)
self.color = color
def meow(self) -> str:
return f"{self.name} 喵喵叫! 🐱"
def get_info(self) -> str:
return f"{super().get_info()}, 毛色: {self.color}, 类型: 猫"
if __name__ == "__main__":
dog = Dog("旺财", 3, "金毛")
cat = Cat("咪咪", 2, "橘色")
print("=== 继承演示 ===")
print(dog.get_info())
print(dog.eat())
print(dog.bark())
print()
print(cat.get_info())
print(cat.sleep())
print(cat.meow())
print()
print(f"旺财是Animal? {isinstance(dog, Animal)}")
print(f"旺财是Dog? {isinstance(dog, Dog)}")
print(f"旺财是Cat? {isinstance(dog, Cat)}")