Python面向对象编程:动物继承体系解析

一、构建框架(整理思路+设计流程)

1、架构设计思路

继承关系设

复制代码
Animal (基类)
│
├── Mammal (继承自Animal)
│   │
│   └── Feline (继承自Mammal)
│       │
│       ├── Lion (继承自Feline)
│       │
│       └── DomesticCat (继承自Feline)
  1. 职责划分原则

    • 基类(Animal):所有动物的共性(名称、年龄、基础行为)
    • 中间类(Mammal/Feline):分类特征(毛发、爪子等)
    • 具体类(Lion/DomesticCat):物种特有属性和行为

2、核心类设计规范

1. 基类 Animal

python 复制代码
class Animal:
    """所有动物的基类,定义共性"""
    def __init__(self, name: str, age: int):
        self.name = name  # 名称强制字符串类型
        self.age = age    # 年龄强制整数类型

    # 必须实现的基础方法
    def eat(self) -> None: ...
    def sleep(self) -> None: ...

2. 中间类 Mammal

python 复制代码
class Mammal(Animal):
    """哺乳动物特有属性"""
    def __init__(self, name: str, age: int, fur_color: str):
        super().__init__(name, age)
        self.fur_color = fur_color  # 毛发颜色
    
    def nurse(self) -> None:  # 哺乳行为
        """哺乳动物特有方法"""

3. 终端类示例 Lion

python 复制代码
class Lion(Feline):
    def roar(self) -> None:
        """狮子特有行为"""
        print(f"{self.name}的吼声响彻草原!")  # 强化行为描述

4.框架核心特点

特点 你的代码体现 生活比喻
继承 class Lion(Feline) 精装房继承毛坯房的所有基础
封装 把属性藏在类内部(self.name 房子的电路藏在墙里
多态 所有动物都有eat()但实现可能不同 不同房间的门窗开关方式不同

3.执行流程设计

初始化流程

python 复制代码
用户输入 → 参数验证 → 实例化具体类 → 返回对象

方法调用流程

python 复制代码
lion = Lion("辛巴", 5, "金色", 5, "巨大")
lion.eat()  # 调用链:Lion → Feline → Mammal → Animal

二、代码解析

1. 最底层:Animal类(所有动物的蓝图)

python 复制代码
class Animal:
    def __init__(self, name, age):  # 构造函数
        self.name = name  # 所有动物都有名字
        self.age = age    # 所有动物都有年龄

    def eat(self):  # 基础行为
        print(f"{self.name}正在吃东西") 

    def sleep(self):  # 基础行为
        print(f"{self.name}正在睡觉")

💡 重点理解:

  • __init__:创建动物时必须提供名字和年龄(就像出生证明)
  • self:代表动物自己(好比说"我今年X岁"中的"我")
  • 方法:所有动物共有的行为(吃和睡)

➡️ 实例化测试:

python 复制代码
dog = Animal("阿黄", 3)
dog.eat()  # 输出:阿黄正在吃东西

2. 第一层继承:Mammal类(哺乳动物升级包)

python 复制代码
class Mammal(Animal):  # 继承Animal的所有功能
    def __init__(self, name, age, fur_color):
        super().__init__(name, age)  # 先调用父类的初始化
        self.fur_color = fur_color  # 新增属性

    def nurse(self):  # 新增方法
        print(f"{self.name}正在哺乳幼崽")

🔑 关键点:

  • super():获取父类的能力(先有动物基础,再加哺乳特性)
  • 扩展 :在动物基础上增加了fur_color属性和nurse()方法

➡️ 实例化测试:

python 复制代码
whale = Mammal("大白", 5, "蓝色")
whale.nurse()  # 输出:大白正在哺乳幼崽
whale.eat()    # 仍可用父类方法

3. 第二层继承:Feline类(猫科动物专属特性)

python 复制代码
class Feline(Mammal):
    def __init__(self, name, age, fur_color, claw_length):
        super().__init__(name, age, fur_color)
        self.claw_length = claw_length  # 猫科特有属性

    def purr(self):  # 猫科特有行为
        print(f"{self.name}正在发出呼噜声")

🌟 特性:

  • 继承链:Feline → Mammal → Animal
  • 独有的爪子长度属性和呼噜声方法

➡️ 实例化测试:

python 复制代码
tiger = Feline("泰哥", 4, "橙色条纹", 5)
tiger.purr()  # 输出:泰哥正在发出呼噜声
tiger.sleep() # 仍可用最底层的方法

4. 最具体实现:Lion和DomesticCat(最终形态)

🦁 Lion类:
python 复制代码
class Lion(Feline):
    def __init__(self, name, age, fur_color, claw_length, mane_size):
        super().__init__(name, age, fur_color, claw_length)
        self.mane_size = mane_size  # 狮子特有属性

    def roar(self):  # 狮子特有行为
        print(f"{self.name}正在吼叫!")

🐈 DomesticCat类:

python 复制代码
class DomesticCat(Feline):
    def __init__(self, name, age, fur_color, claw_length, owner):
        super().__init__(name, age, fur_color, claw_length)
        self.owner = owner  # 家猫特有属性

    def meow(self):  # 家猫特有行为
        print(f"{self.name}对着{self.owner}喵喵叫")

🌈 特点对比:

特有属性 特有方法 继承自
Lion mane_size roar() Feline
DomesticCat owner meow() Feline

5. 代码执行流程(main部分)

python 复制代码
if __name__ == "__main__":
    # 创建实例并测试
    lion = Lion("辛巴", 5, "金色", 5, "巨大")
    lion.roar()  # 调用狮子特有方法
    lion.eat()   # 调用继承自Animal的方法

    cat = DomesticCat("小花", 2, "三色", 1, "小明")
    cat.meow()

🔍 执行顺序示例(以lion.eat()为例):

  1. 查找Lion类是否有eat() → 没有
  2. 向上查找父类Feline → 没有
  3. 继续查找Mammal → 没有
  4. 最后在Animal类中找到 → 执行

三、完整代码

python 复制代码
class Animal:
    """基础动物类"""
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(f"{self.name}正在吃东西")

    def sleep(self):
        print(f"{self.name}正在睡觉")

    def __str__(self):
        return f"动物: {self.name}, 年龄: {self.age}岁"

class Mammal(Animal):
    """哺乳动物类,继承自动物类"""
    def __init__(self, name, age, fur_color):
        super().__init__(name, age)
        self.fur_color = fur_color

    def nurse(self):
        print(f"{self.name}正在哺乳幼崽")

    def __str__(self):
        return f"哺乳动物: {self.name}, 年龄: {self.age}岁, 毛发颜色: {self.fur_color}"

class Feline(Mammal):
    """猫科动物类,继承自哺乳动物类"""
    def __init__(self, name, age, fur_color, claw_length):
        super().__init__(name, age, fur_color)
        self.claw_length = claw_length

    def purr(self):
        print(f"{self.name}正在发出呼噜声")

    def scratch(self):
        print(f"{self.name}正在用{self.claw_length}cm长的爪子抓东西")  # 修正了括号

    def __str__(self):
        return (f"猫科动物: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm")

class Lion(Feline):
    """狮子类,继承自猫科动物类"""
    def __init__(self, name, age, fur_color, claw_length, mane_size):
        super().__init__(name, age, fur_color, claw_length)
        self.mane_size = mane_size

    def roar(self):
        print(f"{self.name}正在发出震耳欲聋的吼叫!")

    def __str__(self):
        return (f"狮子: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm, "
                f"鬃毛大小: {self.mane_size}")

class DomesticCat(Feline):
    """家猫类,继承自猫科动物类"""
    def __init__(self, name, age, fur_color, claw_length, owner):
        super().__init__(name, age, fur_color, claw_length)
        self.owner = owner

    def meow(self):
        print(f"{self.name}对着{self.owner}喵喵叫")

    def __str__(self):
        return (f"家猫: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm, "
                f"主人: {self.owner}")

if __name__ == "__main__":
    print("\n---基础动物---")
    animal = Animal("无名",2)
    print(animal)
    animal.eat()
    animal.sleep()
    
    print("\n---哺乳动物---")
    mammal = Mammal("哺乳兽", 3, "棕色")
    print(mammal)
    mammal.eat()
    mammal.nurse()
    
    print("\n---猫科动物---")
    feline = Feline("大猫", 4, "条纹", 3)
    print(feline)
    feline.purr()
    feline.scratch()
    
    print("\n---狮子---")
    lion = Lion("辛巴", 5, "金色", 5, "巨大")
    print(lion)
    lion.roar()
    lion.eat()  # 继承自Animal的方法
代码框架是什么,我刚开始接触编程

四、将上述代码变成直接输入

完整代码如下:

python 复制代码
class Animal:
    """基础动物类"""
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(f"{self.name}正在吃东西")

    def sleep(self):
        print(f"{self.name}正在睡觉")

    def __str__(self):
        return f"动物: {self.name}, 年龄: {self.age}岁"

class Mammal(Animal):
    """哺乳动物类,继承自动物类"""
    def __init__(self, name, age, fur_color):
        super().__init__(name, age)
        self.fur_color = fur_color

    def nurse(self):
        print(f"{self.name}正在哺乳幼崽")

    def __str__(self):
        return f"哺乳动物: {self.name}, 年龄: {self.age}岁, 毛发颜色: {self.fur_color}"

class Feline(Mammal):
    """猫科动物类,继承自哺乳动物类"""
    def __init__(self, name, age, fur_color, claw_length):
        super().__init__(name, age, fur_color)
        self.claw_length = claw_length

    def purr(self):
        print(f"{self.name}正在发出呼噜声")

    def scratch(self):
        print(f"{self.name}正在用{self.claw_length}cm长的爪子抓东西")

    def __str__(self):
        return (f"猫科动物: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm")

class Lion(Feline):
    """狮子类,继承自猫科动物类"""
    def __init__(self, name, age, fur_color, claw_length, mane_size):
        super().__init__(name, age, fur_color, claw_length)
        self.mane_size = mane_size

    def roar(self):
        print(f"{self.name}正在发出震耳欲聋的吼叫!")

    def __str__(self):
        return (f"狮子: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm, "
                f"鬃毛大小: {self.mane_size}")

class DomesticCat(Feline):
    """家猫类,继承自猫科动物类"""
    def __init__(self, name, age, fur_color, claw_length, owner):
        super().__init__(name, age, fur_color, claw_length)
        self.owner = owner

    def meow(self):
        print(f"{self.name}对着{self.owner}喵喵叫")

    def __str__(self):
        return (f"家猫: {self.name}, 年龄: {self.age}岁, "
                f"毛发颜色: {self.fur_color}, 爪子长度: {self.claw_length}cm, "
                f"主人: {self.owner}")

def create_animal():
    """创建基础动物"""
    print("\n创建基础动物")
    name = input("请输入动物名称: ")
    age = int(input("请输入动物年龄: "))
    return Animal(name, age)

def create_mammal():
    """创建哺乳动物"""
    print("\n创建哺乳动物")
    name = input("请输入动物名称: ")
    age = int(input("请输入动物年龄: "))
    fur_color = input("请输入毛发颜色: ")
    return Mammal(name, age, fur_color)

def create_feline():
    """创建猫科动物"""
    print("\n创建猫科动物")
    name = input("请输入动物名称: ")
    age = int(input("请输入动物年龄: "))
    fur_color = input("请输入毛发颜色: ")
    claw_length = float(input("请输入爪子长度(cm): "))
    return Feline(name, age, fur_color, claw_length)

def create_lion():
    """创建狮子"""
    print("\n创建狮子")
    name = input("请输入狮子名称: ")
    age = int(input("请输入狮子年龄: "))
    fur_color = input("请输入毛发颜色: ")
    claw_length = float(input("请输入爪子长度(cm): "))
    mane_size = input("请输入鬃毛大小(小/中/大/巨大): ")
    return Lion(name, age, fur_color, claw_length, mane_size)

def create_domestic_cat():
    """创建家猫"""
    print("\n创建家猫")
    name = input("请输入猫咪名称: ")
    age = int(input("请输入猫咪年龄: "))
    fur_color = input("请输入毛发颜色: ")
    claw_length = float(input("请输入爪子长度(cm): "))
    owner = input("请输入主人姓名: ")
    return DomesticCat(name, age, fur_color, claw_length, owner)

def main():
    animals = []
    
    while True:
        print("\n动物王国创建系统")
        print("1. 创建基础动物")
        print("2. 创建哺乳动物")
        print("3. 创建猫科动物")
        print("4. 创建狮子")
        print("5. 创建家猫")
        print("6. 查看所有动物")
        print("7. 退出")
        
        choice = input("请选择操作(1-7): ")
        
        if choice == '1':
            animals.append(create_animal())
        elif choice == '2':
            animals.append(create_mammal())
        elif choice == '3':
            animals.append(create_feline())
        elif choice == '4':
            animals.append(create_lion())
        elif choice == '5':
            animals.append(create_domestic_cat())
        elif choice == '6':
            print("\n=== 所有动物 ===")
            for animal in animals:
                print(animal)
                # 根据类型调用特定方法
                if isinstance(animal, Lion):
                    animal.roar()
                elif isinstance(animal, DomesticCat):
                    animal.meow()
                elif isinstance(animal, Feline):
                    animal.purr()
                elif isinstance(animal, Mammal):
                    animal.nurse()
                animal.eat()
                animal.sleep()
                print()
        elif choice == '7':
            print("退出系统")
            break
        else:
            print("无效输入,请重新选择")

if __name__ == '__main__':
    main()

1. 类继承体系(核心框架)

python 复制代码
classDiagram
    Animal <|-- Mammal
    Mammal <|-- Feline
    Feline <|-- Lion
    Feline <|-- DomesticCat
各层级功能:
  • Animal :所有动物的基类
    • 基础属性:name, age
    • 基础方法:eat(), sleep()
  • Mammal :哺乳动物
    • 新增属性:fur_color
    • 新增方法:nurse()
  • Feline :猫科动物
    • 新增属性:claw_length
    • 新增方法:purr(), scratch()
  • Lion :狮子
    • 新增属性:mane_size
    • 新增方法:roar()
  • DomesticCat :家猫
    • 新增属性:owner
    • 新增方法:meow()

2. 用户交互系统

程序通过以下函数实现用户交互:

创建函数:
python 复制代码
def create_animal()  # 创建基础动物
def create_mammal()  # 创建哺乳动物
def create_feline()  # 创建猫科动物
def create_lion()    # 创建狮子
def create_domestic_cat()  # 创建家猫

每个创建函数都会:

  1. 打印创建提示
  2. 通过input()获取用户输入
  3. 返回对应类的实例
主控制函数:
python 复制代码
def main():
    animals = []  # 存储所有创建的动物
    while True:
        # 打印菜单
        choice = input("请选择操作(1-7): ")
        
        # 处理用户选择
        if choice == '1':
            animals.append(create_animal())
        # ...其他选项处理...
        elif choice == '6':
            # 显示所有动物信息
            for animal in animals:
                print(animal)
                # 调用特有方法
                if isinstance(animal, Lion):
                    animal.roar()
                # ...其他类型判断...
        elif choice == '7':
            break  # 退出

3. 关键编程技巧

继承与多态:
  • 使用super().__init__()调用父类初始化方法
  • 子类自动继承父类的所有方法和属性
  • 通过isinstance()检查对象类型并调用特定方法
用户输入处理:
  • 使用input()获取用户输入
  • 使用int()/float()进行类型转换
  • 基本的输入验证(虽然这里比较简单)
对象管理:
  • 使用列表animals存储所有创建的动物实例
  • 动态添加对象:animals.append(new_animal)

4. 程序执行流程

  1. 启动程序,进入main()函数
  2. 显示主菜单,等待用户输入
  3. 根据用户选择:
    • 1-5:调用对应的创建函数,添加新动物
    • 6:遍历显示所有动物信息
    • 7:退出程序
  4. 循环直到用户选择退出
相关推荐
yz_518 Nemo3 分钟前
Django项目实战
后端·python·django
编程乐趣4 分钟前
C#实现图片文字识别
开发语言·c#
mengyoufengyu11 分钟前
python3:线程管理进程
开发语言·python
西猫雷婶28 分钟前
python学智能算法(十二)|机器学习朴素贝叶斯方法初步-拉普拉斯平滑计算条件概率
开发语言·人工智能·python·深度学习·机器学习·矩阵
是紫焅呢1 小时前
C函数基础.go
开发语言·后端·青少年编程·golang·学习方法·visual studio code
小白杨树树1 小时前
【JAVA】的SPI机制
java·开发语言·microsoft
GuokLiu1 小时前
250618-通过Artifacts功能集成Open-WebUI与Gradio
python·gradio·openwebui
alpszero2 小时前
使用YOLO模型进行线程安全推理
python·yolo
虾球xz2 小时前
CppCon 2017 学习:10 Core Guidelines You Need to Start Using Now
开发语言·c++·学习
cainiao0806052 小时前
基于Python的气象数据分析及可视化研究
开发语言·python·数据分析