Python3:面向对象编程
这里写目录标题
- 🧩 面向对象编程:让代码化身为积木世界
- 一、核心概念:类与对象
- 二、四大基石:面向对象的核心特性
- 1️⃣ 封装(Encapsulation):包装复杂性,提供简单接口
- 2️⃣ 继承(Inheritance):站在巨人的肩膀上
- 3️⃣ 多态(Polymorphism):一个接口,多种形态
- 4️⃣ 抽象(Abstraction):提炼共性,忽略细节
- 三、特殊方法(魔术方法):Python类的超能力
- 四、属性装饰器:优雅地访问和修改属性
- 五、类方法与静态方法:超越实例的方法
- 六、组合与继承:两种代码复用的方式
- 七、单例模式:确保类只有一个实例
- 八、多重继承与MRO:处理复杂继承关系
- 九、设计模式:解决常见问题的经验总结
- 工厂模式:创建对象的接口
- 观察者模式:对象状态变化时通知其他对象
- 实际项目应用:小型代码管理系统
- 总结
- 练习
- 1. 创建一个动物园系统
- 2.实现一个简单的银行系统
- 3.开发一个命令行游戏
- 4.创建一个自定义容器
🧩 面向对象编程:让代码化身为积木世界
想象一下,如果编程是搭建乐高积木,那么面向对象编程(OOP)就是创造了一套可以自定义形状、功能和行为的积木系统。不再局限于使用现成的积木,你可以设计自己的积木类型!
一、核心概念:类与对象
类(Class) 是蓝图,对象(Object) 是实体。
想象你有一个"蛋糕模具"(类),你可以用它制作出无数个"蛋糕"(对象)。每个蛋糕都有相同的基本结构(属性),但可以有不同的口味、装饰(状态)。
# 定义一个蛋糕类
class Cake:def __init__(self, flavor, layers):self.flavor = flavor # 属性:口味self.layers = layers # 属性:层数self.is_baked = False # 属性:是否烤好def bake(self, time): # 方法:烘焙print(f"烘焙{self.flavor}蛋糕 {time} 分钟...")self.is_baked = Truedef add_topping(self, topping): # 方法:添加装饰print(f"在{self.flavor}蛋糕上添加{topping}")# 创建两个不同的蛋糕对象
chocolate_cake = Cake("巧克力", 3)
strawberry_cake = Cake("草莓", 2)# 使用对象的方法
chocolate_cake.bake(30)
chocolate_cake.add_topping("巧克力碎片")strawberry_cake.bake(25)
strawberry_cake.add_topping("新鲜草莓")
二、四大基石:面向对象的核心特性
1️⃣ 封装(Encapsulation):包装复杂性,提供简单接口
就像使用咖啡机,你只需要按按钮,不需要了解内部工作原理。封装让我们隐藏复杂的实现细节,只暴露必要的功能。
class BankAccount:def __init__(self, owner, initial_balance=0):self.owner = ownerself.__balance = initial_balance # 私有属性,外部不能直接访问def deposit(self, amount):if amount > 0:self.__balance += amountreturn Truereturn Falsedef withdraw(self, amount):if 0 < amount <= self.__balance:self.__balance -= amountreturn Truereturn Falsedef get_balance(self):return self.__balance # 通过方法访问私有属性# 使用银行账户
account = BankAccount("张三", 1000)
account.deposit(500)
print(account.get_balance()) # 1500# 无法直接访问私有属性
# print(account.__balance) # 这会报错!
在Python中,单下划线(_
)表示"内部使用",双下划线(__
)表示"私有"。实际上,Python会将__balance
转换为_BankAccount__balance
,这种命名改写称为名称修饰(name mangling)。
2️⃣ 继承(Inheritance):站在巨人的肩膀上
继承允许一个类(子类)获得另一个类(父类)的所有属性和方法。这就像孩子继承了父母的特征,但可以发展自己的特性。
# 父类
class Animal:def __init__(self, name, species):self.name = nameself.species = speciesdef make_sound(self):print("某种动物声音")def info(self):print(f"我是{self.name},一只{self.species}")# 子类
class Dog(Animal):def __init__(self, name, breed):# 调用父类的初始化方法super().__init__(name, "狗")self.breed = breed# 重写父类方法def make_sound(self):print("汪汪!")# 添加新方法def fetch(self):print(f"{self.name}去捡球了!")# 创建对象
animal = Animal("未知", "某种动物")
dog = Dog("旺财", "金毛")animal.info() # 我是未知,一只某种动物
dog.info() # 我是旺财,一只狗animal.make_sound() # 某种动物声音
dog.make_sound() # 汪汪!dog.fetch() # 旺财去捡球了!
3️⃣ 多态(Polymorphism):一个接口,多种形态
多态允许不同类的对象对同一消息做出不同的响应。这就像按下"播放"按钮,音乐播放器播放音乐,视频播放器播放视频。
# 继续使用前面的Animal类体系
def make_animal_sound(animal):animal.make_sound() # 不关心具体是什么动物,只调用make_sound方法class Cat(Animal):def __init__(self, name, color):super().__init__(name, "猫")self.color = colordef make_sound(self):print("喵喵!")# 创建不同动物
dog = Dog("旺财", "金毛")
cat = Cat("咪咪", "橘色")# 同一个函数可以处理不同类型的对象
make_animal_sound(dog) # 汪汪!
make_animal_sound(cat) # 喵喵!
4️⃣ 抽象(Abstraction):提炼共性,忽略细节
抽象让我们专注于对象的"是什么"和"能做什么",而不是"怎么做"。在Python中,我们可以通过abc
模块实现抽象类。
from abc import ABC, abstractmethodclass Shape(ABC):@abstractmethoddef area(self):pass@abstractmethoddef perimeter(self):passclass Circle(Shape):def __init__(self, radius):self.radius = radiusdef area(self):return 3.14 * self.radius * self.radiusdef perimeter(self):return 2 * 3.14 * self.radiusclass Rectangle(Shape):def __init__(self, length, width):self.length = lengthself.width = widthdef area(self):return self.length * self.widthdef perimeter(self):return 2 * (self.length + self.width)# 不能创建抽象类的实例
# shape = Shape() # 这会报错!# 创建具体形状
circle = Circle(5)
rectangle = Rectangle(4, 6)print(f"圆的面积: {circle.area()}")
print(f"矩形的面积: {rectangle.area()}")
三、特殊方法(魔术方法):Python类的超能力
Python类有许多特殊方法,以双下划线开头和结尾,如__init__
、__str__
等。这些方法可以让我们自定义对象的行为。
class Book:def __init__(self, title, author, pages):self.title = titleself.author = authorself.pages = pagesself.current_page = 0# 定义对象的字符串表示def __str__(self):return f"{self.title} by {self.author}"# 定义对象的官方表示def __repr__(self):return f"Book('{self.title}', '{self.author}', {self.pages})"# 定义对象的长度def __len__(self):return self.pages# 定义对象的布尔值def __bool__(self):return self.pages > 0# 使对象可以像函数一样被调用def __call__(self, page):if 0 <= page < self.pages:self.current_page = pagereturn f"翻到了第{page}页"return "无效页码"# 创建书籍对象
book = Book("Python大冒险", "编程达人", 300)print(str(book)) # Python大冒险 by 编程达人
print(repr(book)) # Book('Python大冒险', '编程达人', 300)
print(len(book)) # 300
print(bool(book)) # True
print(book(100)) # 翻到了第100页
四、属性装饰器:优雅地访问和修改属性
使用属性装饰器,我们可以像访问属性一样调用方法,使代码更加简洁优雅。
class Temperature:def __init__(self, celsius=0):self._celsius = celsius@propertydef celsius(self):return self._celsius@celsius.setterdef celsius(self, value):if value < -273.15:raise ValueError("温度不能低于绝对零度")self._celsius = value@propertydef fahrenheit(self):return self._celsius * 9/5 + 32@fahrenheit.setterdef fahrenheit(self, value):self.celsius = (value - 32) * 5/9# 创建温度对象
temp = Temperature(25)# 像访问属性一样使用getter
print(temp.celsius) # 25
print(temp.fahrenheit) # 77.0# 像修改属性一样使用setter
temp.celsius = 30
print(temp.fahrenheit) # 86.0temp.fahrenheit = 68
print(temp.celsius) # 20.0# 设置无效温度会引发异常
# temp.celsius = -300 # ValueError: 温度不能低于绝对零度
五、类方法与静态方法:超越实例的方法
除了常规的实例方法,Python类还可以有类方法和静态方法。
class Pizza:total_pizzas = 0 # 类变量def __init__(self, size, toppings):self.size = sizeself.toppings = toppingsPizza.total_pizzas += 1# 实例方法:需要访问实例属性def get_description(self):toppings_str = ", ".join(self.toppings)return f"{self.size}寸披萨,配料:{toppings_str}"# 类方法:需要访问类属性@classmethoddef get_total(cls):return f"总共制作了{cls.total_pizzas}个披萨"# 类方法作为替代构造函数@classmethoddef create_cheese_pizza(cls, size):return cls(size, ["奶酪"])# 静态方法:不需要访问实例或类属性@staticmethoddef is_valid_size(size):return size in [6, 9, 12, 18]# 创建披萨
pizza1 = Pizza(12, ["奶酪", "蘑菇", "青椒"])
pizza2 = Pizza(9, ["奶酪", "香肠"])# 调用实例方法
print(pizza1.get_description()) # 12寸披萨,配料:奶酪, 蘑菇, 青椒# 调用类方法
print(Pizza.get_total()) # 总共制作了2个披萨# 使用类方法作为替代构造函数
cheese_pizza = Pizza.create_cheese_pizza(18)
print(cheese_pizza.get_description()) # 18寸披萨,配料:奶酪# 调用静态方法
print(Pizza.is_valid_size(12)) # True
print(Pizza.is_valid_size(7)) # False
六、组合与继承:两种代码复用的方式
继承表示"是一个"关系,组合表示"有一个"关系。通常,组合比继承更灵活。
# 组合示例
class Engine:def __init__(self, power):self.power = powerdef start(self):return f"引擎启动,功率{self.power}马力"class Radio:def __init__(self, brand):self.brand = branddef play_music(self):return f"{self.brand}音响播放音乐"# 汽车通过组合使用引擎和收音机
class Car:def __init__(self, model, engine_power, radio_brand):self.model = modelself.engine = Engine(engine_power) # 组合self.radio = Radio(radio_brand) # 组合def start_journey(self):return f"{self.model}:{self.engine.start()},{self.radio.play_music()}"# 创建汽车
my_car = Car("特斯拉Model 3", 300, "哈曼卡顿")
print(my_car.start_journey())
# 特斯拉Model 3:引擎启动,功率300马力,哈曼卡顿音响播放音乐
七、单例模式:确保类只有一个实例
有时我们需要确保一个类只有一个实例,比如配置管理器、数据库连接池等。
class Singleton:_instance = Nonedef __new__(cls, *args, **kwargs):if cls._instance is None:cls._instance = super().__new__(cls)return cls._instanceclass ConfigManager(Singleton):def __init__(self):# 这里仅在第一次创建实例时初始化if not hasattr(self, 'config'):self.config = {'debug': True,'log_level': 'INFO','max_connections': 100}def get_config(self, key):return self.config.get(key)def set_config(self, key, value):self.config[key] = value# 创建两个实例
config1 = ConfigManager()
config2 = ConfigManager()# 它们是同一个对象
print(config1 is config2) # True# 通过一个实例修改配置
config1.set_config('debug', False)# 另一个实例也会受到影响
print(config2.get_config('debug')) # False
八、多重继承与MRO:处理复杂继承关系
Python允许一个类继承多个父类,但这可能导致方法解析顺序(MRO)的问题。
class A:def who_am_i(self):return "I am A"class B(A):def who_am_i(self):return "I am B"class C(A):def who_am_i(self):return "I am C"# D同时继承B和C
class D(B, C):pass# 查看MRO
print(D.__mro__)
# (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)# 调用方法
d = D()
print(d.who_am_i()) # I am B (因为B在MRO中排在C前面)
九、设计模式:解决常见问题的经验总结
面向对象编程中,设计模式是对常见问题的解决方案。以下是一些常见的设计模式:
工厂模式:创建对象的接口
class Animal:def speak(self):passclass Dog(Animal):def speak(self):return "汪汪!"class Cat(Animal):def speak(self):return "喵喵!"class AnimalFactory:def create_animal(self, animal_type):if animal_type == "dog":return Dog()elif animal_type == "cat":return Cat()else:raise ValueError(f"不支持的动物类型: {animal_type}")# 使用工厂
factory = AnimalFactory()
dog = factory.create_animal("dog")
cat = factory.create_animal("cat")print(dog.speak()) # 汪汪!
print(cat.speak()) # 喵喵!
观察者模式:对象状态变化时通知其他对象
class Subject:def __init__(self):self._observers = []def attach(self, observer):if observer not in self._observers:self._observers.append(observer)def detach(self, observer):self._observers.remove(observer)def notify(self, message):for observer in self._observers:observer.update(message)class Observer:def __init__(self, name):self.name = namedef update(self, message):print(f"{self.name} 收到消息: {message}")# 创建主题和观察者
subject = Subject()
observer1 = Observer("观察者1")
observer2 = Observer("观察者2")# 添加观察者
subject.attach(observer1)
subject.attach(observer2)# 通知观察者
subject.notify("你好,世界!")
# 观察者1 收到消息: 你好,世界!
# 观察者2 收到消息: 你好,世界!# 移除观察者
subject.detach(observer1)
subject.notify("再见!")
# 观察者2 收到消息: 再见!
实际项目应用:小型代码管理系统
让我们将所学知识应用到一个小型的代码版本管理系统:
from datetime import datetime
import uuidclass CodeFile:def __init__(self, name, content=""):self.name = nameself.content = contentself.created_at = datetime.now()self.updated_at = self.created_atdef update_content(self, content):self.content = contentself.updated_at = datetime.now()def __str__(self):return f"文件: {self.name}, 最后更新: {self.updated_at}"class Commit:def __init__(self, message, author):self.id = str(uuid.uuid4())[:8] # 生成短UUIDself.message = messageself.author = authorself.timestamp = datetime.now()self.files = {} # 文件快照def add_file(self, file):# 创建文件的快照 (深拷贝)snapshot = CodeFile(file.name, file.content)self.files[file.name] = snapshotdef __str__(self):return f"提交 {self.id}: {self.message} by {self.author} at {self.timestamp}"class Repository:def __init__(self, name):self.name = nameself.files = {} # 当前工作区文件self.commits = [] # 提交历史def create_file(self, name, content=""):if name in self.files:raise ValueError(f"文件 {name} 已存在")self.files[name] = CodeFile(name, content)return self.files[name]def update_file(self, name, content):if name not in self.files:raise ValueError(f"文件 {name} 不存在")self.files[name].update_content(content)return self.files[name]def commit(self, message, author):commit = Commit(message, author)for file in self.files.values():commit.add_file(file)self.commits.append(commit)return commitdef get_file_history(self, file_name):history = []for commit in self.commits:if file_name in commit.files:history.append({'commit': commit,'content': commit.files[file_name].content})return historydef __str__(self):return f"仓库: {self.name}, 文件数: {len(self.files)}, 提交数: {len(self.commits)}"# 使用示例
repo = Repository("我的项目")# 创建文件
hello_py = repo.create_file("hello.py", "print('Hello, World!')")
readme = repo.create_file("README.md", "# 我的项目\n这是一个示例项目。")# 提交
repo.commit("初始提交", "张三")# 更新文件
repo.update_file("hello.py", "print('Hello, Python!')\nprint('Welcome to OOP!')")
repo.commit("更新 hello.py", "张三")# 查看仓库信息
print(repo) # 仓库: 我的项目, 文件数: 2, 提交数: 2# 查看文件历史
history = repo.get_file_history("hello.py")
for entry in history:print(f"{entry['commit'].id}: {entry['content']}")
总结
面向对象编程是Python强大的编程范式之一,通过类和对象的概念,可以将复杂问题分解为易于管理的部分。关键点包括:
- 类与对象:类是定义,对象是实例
- 四大支柱:封装、继承、多态、抽象
- 特殊方法:使类更"Pythonic"
- 属性装饰器:方法伪装成属性
- 类方法与静态方法:超越实例的功能
- 组合与继承:代码复用的两种方式
- 设计模式:解决常见问题的模式
掌握这些概念后,你就可以设计出结构清晰、易于维护的代码,为更高级的Python应用打下坚实基础!
练习
-
创建一个动物园系统
- Implement a Zoo class that manages different animal classes
- Practice inheritance and polymorphism
-
实现一个简单的银行系统
- Account classes with different types
- Transaction tracking and account management
-
开发一个命令行游戏
- Use classes for game objects and states
- Practice encapsulation and abstraction
-
创建一个自定义容器类
- Implement special methods like
__getitem__
,__setitem__
, etc. - Make your container behave like a list or dictionary
- Implement special methods like
记住,理解概念很重要,但真正掌握面向对象编程需要大量实践。从简单的项目开始,逐步挑战更复杂的问题!
1. 创建一个动物园系统
# 动物园系统实现class Animal:"""动物基类"""def __init__(self, name, age, health=100, hunger=0):self.name = nameself.age = ageself.health = healthself.hunger = hungerdef make_sound(self):"""动物发出声音"""passdef eat(self, food_amount):"""动物进食"""self.hunger = max(0, self.hunger - food_amount)print(f"{self.name} has eaten. Hunger level: {self.hunger}")def update_status(self):"""更新动物状态"""self.hunger += 10if self.hunger > 100:self.health -= 10print(f"{self.name} is too hungry and losing health!")def __str__(self):return f"{self.__class__.__name__}: {self.name}, Age: {self.age}, Health: {self.health}, Hunger: {self.hunger}"class Mammal(Animal):"""哺乳动物类"""def __init__(self, name, age, fur_color, health=100, hunger=0):super().__init__(name, age, health, hunger)self.fur_color = fur_colordef give_birth(self):"""哺乳动物生育"""print(f"{self.name} has given birth to a baby!")class Bird(Animal):"""鸟类"""def __init__(self, name, age, wing_span, health=100, hunger=0):super().__init__(name, age, health, hunger)self.wing_span = wing_spandef fly(self):"""鸟类飞行"""print(f"{self.name} is flying with a wingspan of {self.wing_span}cm!")class Lion(Mammal):"""狮子类"""def make_sound(self):return "ROAR!"def hunt(self):"""狮子捕猎"""self.hunger = max(0, self.hunger - 30)print(f"{self.name} has hunted successfully. Hunger decreased to {self.hunger}")class Parrot(Bird):"""鹦鹉类"""def __init__(self, name, age, wing_span, vocabulary=None, health=100, hunger=0):super().__init__(name, age, wing_span, health, hunger)self.vocabulary = vocabulary or []def make_sound(self):return "Squawk!"def talk(self):"""鹦鹉说话"""if not self.vocabulary:return f"{self.name} doesn't know any words yet."return f"{self.name} says: {self.vocabulary[0]}"def learn_word(self, word):"""鹦鹉学习新词"""self.vocabulary.append(word)print(f"{self.name} learned a new word: {word}")class Zoo:"""动物园类"""def __init__(self, name):self.name = nameself.animals = {}self.animal_count = 0def add_animal(self, animal):"""添加动物到动物园"""self.animal_count += 1animal_id = self.animal_countself.animals[animal_id] = animalprint(f"{animal.name} has been added to {self.name} Zoo with ID: {animal_id}")return animal_iddef remove_animal(self, animal_id):"""从动物园移除动物"""if animal_id in self.animals:animal = self.animals.pop(animal_id)print(f"{animal.name} has been removed from {self.name} Zoo")return Truereturn Falsedef feed_animal(self, animal_id, food_amount):"""喂养动物"""if animal_id in self.animals:self.animals[animal_id].eat(food_amount)return Truereturn Falsedef update_all_animals(self):"""更新所有动物状态"""print(f"Updating all animals in {self.name} Zoo...")for animal in self.animals.values():animal.update_status()def get_animal_sounds(self):"""获取所有动物的声音"""sounds = {}for animal_id, animal in self.animals.items():sounds[animal_id] = animal.make_sound()return soundsdef __str__(self):result = f"{self.name} Zoo with {len(self.animals)} animals:\n"for animal_id, animal in self.animals.items():result += f"ID {animal_id}: {animal}\n"return result# 测试代码
if __name__ == "__main__":# 创建动物园central_zoo = Zoo("Central")# 创建动物simba = Lion("Simba", 5, "Golden", health=95, hunger=20)nala = Lion("Nala", 4, "Tan")polly = Parrot("Polly", 2, 30, ["Hello", "Goodbye"])# 添加动物到动物园simba_id = central_zoo.add_animal(simba)nala_id = central_zoo.add_animal(nala)polly_id = central_zoo.add_animal(polly)# 测试动物行为print(simba.make_sound()) # ROAR!simba.hunt() # 狮子捕猎polly.learn_word("I'm hungry!") # 鹦鹉学习新词print(polly.talk()) # 鹦鹉说话# 喂养动物central_zoo.feed_animal(nala_id, 30)# 更新所有动物状态central_zoo.update_all_animals()# 打印动物园信息print(central_zoo)# 获取所有动物的声音sounds = central_zoo.get_animal_sounds()for animal_id, sound in sounds.items():animal = central_zoo.animals[animal_id]print(f"Animal ID {animal_id} ({animal.name}) says: {sound}")
2.实现一个简单的银行系统
# 银行系统实现import datetime
from abc import ABC, abstractmethod
import uuidclass Transaction:"""交易类"""def __init__(self, amount, description, transaction_type):self.transaction_id = str(uuid.uuid4())[:8] # 生成唯一交易IDself.amount = amountself.description = descriptionself.timestamp = datetime.datetime.now()self.transaction_type = transaction_type # "deposit", "withdrawal", "transfer"def __str__(self):return f"[{self.timestamp.strftime('%Y-%m-%d %H:%M:%S')}] {self.transaction_type.upper()}: {self.amount:.2f} - {self.description} (ID: {self.transaction_id})"class Account(ABC):"""账户抽象基类"""def __init__(self, account_number, owner_name, balance=0):self.account_number = account_numberself.owner_name = owner_nameself._balance = balanceself.transactions = []@propertydef balance(self):"""获取账户余额"""return self._balancedef deposit(self, amount, description="Deposit"):"""存款"""if amount <= 0:raise ValueError("Deposit amount must be positive")self._balance += amounttransaction = Transaction(amount, description, "deposit")self.transactions.append(transaction)return transactiondef withdraw(self, amount, description="Withdrawal"):"""取款"""if amount <= 0:raise ValueError("Withdrawal amount must be positive")if amount > self._balance:raise ValueError("Insufficient funds")self._balance -= amounttransaction = Transaction(amount, description, "withdrawal")self.transactions.append(transaction)return transactiondef get_transaction_history(self):"""获取交易历史"""return self.transactions@abstractmethoddef get_account_type(self):"""获取账户类型"""passdef __str__(self):return f"{self.get_account_type()} - {self.account_number} ({self.owner_name}): ${self.balance:.2f}"class SavingsAccount(Account):"""储蓄账户类"""def __init__(self, account_number, owner_name, balance=0, interest_rate=0.01):super().__init__(account_number, owner_name, balance)self.interest_rate = interest_ratedef apply_interest(self):"""应用利息"""interest = self._balance * self.interest_rateself.deposit(interest, "Interest applied")return interestdef get_account_type(self):return "Savings Account"class CheckingAccount(Account):"""支票账户类"""def __init__(self, account_number, owner_name, balance=0, overdraft_limit=100):super().__init__(account_number, owner_name, balance)self.overdraft_limit = overdraft_limitdef withdraw(self, amount, description="Withdrawal"):"""支票账户取款,支持透支"""if amount <= 0:raise ValueError("Withdrawal amount must be positive")if amount > (self._balance + self.overdraft_limit):raise ValueError(f"Withdrawal exceeds overdraft limit. Maximum withdrawal: ${self._balance + self.overdraft_limit:.2f}")self._balance -= amounttransaction = Transaction(amount, description, "withdrawal")self.transactions.append(transaction)if self._balance < 0:print(f"Warning: Account {self.account_number} is overdrawn by ${abs(self._balance):.2f}")return transactiondef get_account_type(self):return "Checking Account"class Bank:"""银行类"""def __init__(self, name):self.name = nameself.accounts = {}self.next_account_number = 10000 # 起始账号def create_account(self, owner_name, account_type, initial_deposit=0, **kwargs):"""创建新账户"""account_number = str(self.next_account_number)self.next_account_number += 1if account_type.lower() == "savings":interest_rate = kwargs.get("interest_rate", 0.01)account = SavingsAccount(account_number, owner_name, initial_deposit, interest_rate)elif account_type.lower() == "checking":overdraft_limit = kwargs.get("overdraft_limit", 100)account = CheckingAccount(account_number, owner_name, initial_deposit, overdraft_limit)else:raise ValueError("Invalid account type")self.accounts[account_number] = accountif initial_deposit > 0:account.deposit(initial_deposit, "Initial deposit")print(f"Account created: {account}")return accountdef get_account(self, account_number):"""获取账户"""if account_number not in self.accounts:raise ValueError("Account not found")return self.accounts[account_number]def transfer(self, from_account_number, to_account_number, amount, description="Transfer"):"""账户间转账"""if amount <= 0:raise ValueError("Transfer amount must be positive")from_account = self.get_account(from_account_number)to_account = self.get_account(to_account_number)# 从源账户取款from_transaction = from_account.withdraw(amount, f"Transfer to account {to_account_number}: {description}")# 存入目标账户to_transaction = to_account.deposit(amount, f"Transfer from account {from_account_number}: {description}")return (from_transaction, to_transaction)def apply_interest_to_all_savings(self):"""为所有储蓄账户应用利息"""applied_count = 0total_interest = 0for account in self.accounts.values():if isinstance(account, SavingsAccount):interest = account.apply_interest()total_interest += interestapplied_count += 1print(f"Applied interest to {applied_count} accounts. Total interest: ${total_interest:.2f}")return total_interestdef get_total_deposits(self):"""获取所有账户的总存款额"""return sum(account.balance for account in self.accounts.values())def __str__(self):return f"{self.name} Bank - {len(self.accounts)} accounts, Total deposits: ${self.get_total_deposits():.2f}"# 测试代码
if __name__ == "__main__":# 创建银行chase_bank = Bank("Chase")# 创建账户john_savings = chase_bank.create_account("John Smith", "savings", 1000, interest_rate=0.02)john_checking = chase_bank.create_account("John Smith", "checking", 500, overdraft_limit=200)alice_savings = chase_bank.create_account("Alice Johnson", "savings", 2500)# 测试存款和取款john_savings.deposit(500, "Salary deposit")john_checking.withdraw(200, "ATM withdrawal")try:john_checking.withdraw(1000, "Large purchase")except ValueError as e:print(f"Error: {e}")# 测试转账chase_bank.transfer(john_savings.account_number, alice_savings.account_number, 300, "Debt repayment")# 应用利息chase_bank.apply_interest_to_all_savings()# 打印账户信息print("\nAccount Information:")for account in chase_bank.accounts.values():print(account)# 打印交易历史print("\nTransaction History for John's Savings Account:")for transaction in john_savings.get_transaction_history():print(transaction)# 打印银行信息print("\nBank Information:")print(chase_bank)
3.开发一个命令行游戏
# 命令行冒险游戏实现import random
import time
import sys
from enum import Enum, autoclass GameState(Enum):"""游戏状态枚举"""MAIN_MENU = auto()PLAYING = auto()BATTLE = auto()SHOP = auto()INVENTORY = auto()GAME_OVER = auto()VICTORY = auto()QUIT = auto()class Item:"""物品基类"""def __init__(self, name, description, value):self.name = nameself.description = descriptionself.value = valuedef __str__(self):return f"{self.name} - {self.description} (Value: {self.value} gold)"class Weapon(Item):"""武器类"""def __init__(self, name, description, value, damage):super().__init__(name, description, value)self.damage = damagedef __str__(self):return f"{self.name} - {self.description} (Damage: {self.damage}, Value: {self.value} gold)"class Potion(Item):"""药水类"""def __init__(self, name, description, value, heal_amount):super().__init__(name, description, value)self.heal_amount = heal_amountdef __str__(self):return f"{self.name} - {self.description} (Heals: {self.heal_amount} HP, Value: {self.value} gold)"class Armor(Item):"""护甲类"""def __init__(self, name, description, value, defense):super().__init__(name, description, value)self.defense = defensedef __str__(self):return f"{self.name} - {self.description} (Defense: {self.defense}, Value: {self.value} gold)"class Character:"""角色基类"""def __init__(self, name, hp, attack_power):self.name = nameself.max_hp = hpself.hp = hpself.base_attack = attack_powerdef is_alive(self):"""检查角色是否存活"""return self.hp > 0def take_damage(self, damage):"""受到伤害"""self.hp = max(0, self.hp - damage)return damagedef heal(self, amount):"""恢复生命值"""self.hp = min(self.max_hp, self.hp + amount)return amountdef attack(self, target):"""攻击目标"""damage = self.base_attackreturn target.take_damage(damage)class Player(Character):"""玩家类"""def __init__(self, name, hp=100, attack_power=10):super().__init__(name, hp, attack_power)self.inventory = []self.gold = 50self.weapon = Noneself.armor = Noneself.level = 1self.exp = 0self.exp_to_level = 100def attack(self, target):"""玩家攻击,考虑武器伤害"""damage = self.base_attackif self.weapon:damage += self.weapon.damagereturn target.take_damage(damage)def take_damage(self, damage):"""玩家受到伤害,考虑护甲防御"""if self.armor:damage = max(1, damage - self.armor.defense) # 至少造成1点伤害return super().take_damage(damage)def add_item(self, item):"""添加物品到库存"""self.inventory.append(item)print(f"Added {item.name} to your inventory.")def remove_item(self, item):"""从库存移除物品"""if item in self.inventory:self.inventory.remove(item)return Truereturn Falsedef equip_weapon(self, weapon_index):"""装备武器"""if 0 <= weapon_index < len(self.inventory):item = self.inventory[weapon_index]if isinstance(item, Weapon):old_weapon = self.weaponself.weapon = itemif old_weapon:print(f"Unequipped {old_weapon.name} and equipped {item.name}.")else:print(f"Equipped {item.name}.")return Truereturn Falsedef equip_armor(self, armor_index):"""装备护甲"""if 0 <= armor_index < len(self.inventory):item = self.inventory[armor_index]if isinstance(item, Armor):old_armor = self.armorself.armor = itemif old_armor:print(f"Unequipped {old_armor.name} and equipped {item.name}.")else:print(f"Equipped {item.name}.")return Truereturn Falsedef use_potion(self, potion_index):"""使用药水"""if 0 <= potion_index < len(self.inventory):item = self.inventory[potion_index]if isinstance(item, Potion):healed = self.heal(item.heal_amount)print(f"Used {item.name} and healed for {healed} HP.")self.remove_item(item)return Truereturn Falsedef add_exp(self, amount):"""增加经验值"""self.exp += amountprint(f"Gained {amount} experience points!")# 检查是否升级while self.exp >= self.exp_to_level:self.level_up()def level_up(self):"""升级"""self.exp -= self.exp_to_levelself.level += 1self.max_hp += 20self.hp = self.max_hpself.base_attack += 5self.exp_to_level = int(self.exp_to_level * 1.5)print(f"\n*** LEVEL UP! ***\nYou are now level {self.level}!")print(f"Max HP increased to {self.max_hp}")print(f"Attack increased to {self.base_attack}")def __str__(self):equipped = []if self.weapon:equipped.append(f"Weapon: {self.weapon.name} (+{self.weapon.damage} damage)")if self.armor:equipped.append(f"Armor: {self.armor.name} (+{self.armor.defense} defense)")return (f"{self.name} (Level {self.level})\n"f"HP: {self.hp}/{self.max_hp} | Gold: {self.gold} | EXP: {self.exp}/{self.exp_to_level}\n"f"Attack: {self.base_attack}{' + ' + str(self.weapon.damage) if self.weapon else ''}\n"f"Defense: {self.armor.defense if self.armor else 0}\n"f"Equipped: {', '.join(equipped) if equipped else 'Nothing'}")class Enemy(Character):"""敌人类"""def __init__(self, name, hp, attack_power, gold_reward, exp_reward):super().__init__(name, hp, attack_power)self.gold_reward = gold_rewardself.exp_reward = exp_rewarddef __str__(self):return f"{self.name} (HP: {self.hp}/{self.max_hp}, Attack: {self.base_attack})"class Shop:"""商店类"""def __init__(self):self.inventory = []self.initialize_inventory()def initialize_inventory(self):"""初始化商店库存"""# 武器self.inventory.append(Weapon("Dagger", "A small but sharp dagger", 25, 5))self.inventory.append(Weapon("Sword", "A standard iron sword", 60, 10))self.inventory.append(Weapon("Battle Axe", "A heavy battle axe", 120, 20))# 护甲self.inventory.append(Armor("Leather Armor", "Basic protection made of leather", 40, 5))self.inventory.append(Armor("Chain Mail", "Medium armor made of interlocking rings", 100, 10))self.inventory.append(Armor("Plate Armor", "Heavy armor offering excellent protection", 200, 20))# 药水self.inventory.append(Potion("Minor Healing Potion", "Restores a small amount of health", 15, 20))self.inventory.append(Potion("Healing Potion", "Restores a moderate amount of health", 30, 50))self.inventory.append(Potion("Major Healing Potion", "Restores a large amount of health", 60, 100))def buy_item(self, player, item_index):"""玩家购买物品"""if 0 <= item_index < len(self.inventory):item = self.inventory[item_index]if player.gold >= item.value:player.gold -= item.valueplayer.add_item(item)print(f"You bought {item.name} for {item.value} gold.")return Trueelse:print("You don't have enough gold!")return Falsedef sell_item(self, player, item_index):"""玩家出售物品"""if 0 <= item_index < len(player.inventory):item = player.inventory[item_index]sell_value = item.value // 2 # 卖出价为原价的一半# 确保未装备的物品才能出售if item == player.weapon or item == player.armor:print("You cannot sell equipped items!")return Falseplayer.gold += sell_valueplayer.remove_item(item)print(f"You sold {item.name} for {sell_value} gold.")return Truereturn Falseclass Game:"""游戏主类"""def __init__(self):self.state = GameState.MAIN_MENUself.player = Noneself.current_enemy = Noneself.shop = Shop()self.enemy_types = [{"name": "Goblin", "hp": 30, "attack": 5, "gold": 10, "exp": 20},{"name": "Orc", "hp": 50, "attack": 8, "gold": 15, "exp": 30},{"name": "Troll", "hp": 80, "attack": 12, "gold": 25, "exp": 50},{"name": "Dragon", "hp": 200, "attack": 20, "gold": 100, "exp": 200}]def clear_screen(self):"""清屏"""print("\n" * 50)def slow_print(self, text, delay=0.03):"""缓慢打印文本,增强游戏体验"""for char in text:print(char, end='', flush=True)time.sleep(delay)print()def print_header(self, title):"""打印标题栏"""print("\n" + "=" * 60)print(f"{title:^60}")print("=" * 60 + "\n")def wait_for_input(self):"""等待用户按任意键继续"""input("\nPress Enter to continue...")def show_main_menu(self):"""显示主菜单"""self.clear_screen()self.print_header("DUNGEON ADVENTURE")self.slow_print("Welcome to Dungeon Adventure!", 0.05)print("\n1. New Game")print("2. Quit\n")choice = input("Enter your choice (1-2): ")if choice == "1":self.start_new_game()elif choice == "2":self.state = GameState.QUITelse:print("Invalid choice. Please try again.")self.wait_for_input()def start_new_game(self):"""开始新游戏"""self.clear_screen()self.print_header("CHARACTER CREATION")name = input("Enter your hero's name: ")if not name:name = "Hero"self.player = Player(name)# 给予玩家初始装备starter_weapon = Weapon("Rusty Sword", "An old sword with some rust spots", 0, 3)self.player.add_item(starter_weapon)self.player.equip_weapon(0)starter_potion = Potion("Small Health Potion", "A tiny vial of red liquid", 0, 15)self.player.add_item(starter_potion)self.slow_print(f"\nWelcome, {self.player.name}! Your adventure begins...", 0.05)self.slow_print("You find yourself at the entrance of a dark dungeon.", 0.05)self.slow_print("Legends say it's filled with monsters and treasures.", 0.05)self.slow_print("Are you brave enough to explore it?", 0.05)self.wait_for_input()self.state = GameState.PLAYINGdef show_game_menu(self):"""显示游戏主菜单"""self.clear_screen()self.print_header("DUNGEON ADVENTURE")print(self.player)print("\nWhat would you like to do?")print("1. Explore the dungeon")print("2. Visit the shop")print("3. Check inventory")print("4. Rest (Heal 20% HP)")print("5. Quit to main menu\n")choice = input("Enter your choice (1-5): ")if choice == "1":self.explore()elif choice == "2":self.state = GameState.SHOPelif choice == "3":self.state = GameState.INVENTORYelif choice == "4":self.rest()elif choice == "5":self.state = GameState.MAIN_MENUelse:print("Invalid choice. Please try again.")self.wait_for_input()def explore(self):"""探索地牢"""self.clear_screen()self.print_header("EXPLORING THE DUNGEON")self.slow_print("You venture deeper into the dungeon...", 0.05)time.sleep(1)# 随机事件: 战斗、发现物品、或者什么都没发生event = random.randint(1, 10)if event <= 7: # 70% 概率遇到敌人self.encounter_enemy()elif event <= 9: # 20% 概率发现物品self.find_item()else: # 10% 概率什么都没发生self.slow_print("You explore for a while but find nothing of interest.")self.wait_for_input()def encounter_enemy(self):"""遇到敌人"""# 根据玩家等级选择合适的敌人enemy_level = min(len(self.enemy_types) - 1, self.player.level - 1)enemy_type = self.enemy_types[random.randint(0, enemy_level)]# 根据玩家等级调整敌人属性hp_modifier = 1.0 + (self.player.level - 1) * 0.2attack_modifier = 1.0 + (self.player.level - 1) * 0.1reward_modifier = 1.0 + (self.player.level - 1) * 0.3self.current_enemy = Enemy(enemy_type["name"],int(enemy_type["hp"] * hp_modifier),int(enemy_type["attack"] * attack_modifier),int(enemy_type["gold"] * reward_modifier),int(enemy_type["exp"] * reward_modifier))self.slow_print(f"You encountered a {self.current_enemy.name}!")self.state = GameState.BATTLEdef find_item(self):"""发现物品"""item_type = random.randint(1, 3)if item_type == 1: # 发现金币gold_amount = random.randint(5, 15) * self.player.levelself.player.gold += gold_amountself.slow_print(f"You found a small pouch containing {gold_amount} gold coins!")elif item_type == 2: # 发现药水potion_power = random.randint(1, 3)if potion_power == 1:potion = Potion("Minor Healing Potion", "Restores a small amount of health", 15, 20)elif potion_power == 2:potion = Potion("Healing Potion", "Restores a moderate amount of health", 30, 50)else:potion = Potion("Major Healing Potion", "Restores a large amount of health", 60, 100)self.player.add_item(potion)self.slow_print(f"You found a {potion.name}!")else: # 发现装备equipment_type = random.randint(1, 2)equipment_quality = random.randint(1, 3) * self.player.levelif equipment_type == 1: # 武器weapon_types = ["Dagger", "Sword", "Axe", "Mace", "Spear"]weapon_name = f"{random.choice(['Rusty', 'Iron', 'Steel', 'Silver', 'Enchanted'])} {random.choice(weapon_types)}"weapon = Weapon(weapon_name, f"A {weapon_name.lower()} found in the dungeon", equipment_quality * 10, equipment_quality * 2)self.player.add_item(weapon)self.slow_print(f"You found a {weapon.name}!")else: # 护甲armor_types = ["Armor", "Shield", "Helmet", "Gauntlets", "Boots"]armor_name = f"{random.choice(['Leather', 'Chain', 'Plate', 'Reinforced', 'Magical'])} {random.choice(armor_types)}"armor = Armor(armor_name, f"A {armor_name.lower()} found in the dungeon", equipment_quality * 15, equipment_quality)self.player.add_item(armor)self.slow_print(f"You found a {armor.name}!")self.wait_for_input()def battle(self):"""战斗系统"""self.clear_screen()self.print_header("BATTLE")print(f"{self.player.name}: {self.player.hp}/{self.player.max_hp} HP")print(f"{self.current_enemy.name}: {self.current_enemy.hp}/{self.current_enemy.max_hp} HP\n")print("What will you do?")print("1. Attack")print("2. Use Potion")print("3. Run Away\n")choice = input("Enter your choice (1-3): ")if choice == "1": # 攻击self.player_attack()elif choice == "2": # 使用药水self.use_potion_in_battle()elif choice == "3": # 逃跑if random.random() < 0.7: # 70% 成功率self.slow_print("You successfully escaped!")self.state = GameState.PLAYINGself.wait_for_input()else:self.slow_print("You failed to escape!")self.enemy_attack()else:print("Invalid choice. Please try again.")self.wait_for_input()def player_attack(self):"""玩家攻击"""damage = self.player.attack(self.current_enemy)self.slow_print(f"You attacked the {self.current_enemy.name} and dealt {damage} damage!")if not self.current_enemy.is_alive():self.battle_victory()else:self.enemy_attack()def enemy_attack(self):"""敌人攻击"""damage = self.current_enemy.attack(self.player)self.slow_print(f"The {self.current_enemy.name} attacked you and dealt {damage} damage!")if not self.player.is_alive():self.game_over()else:self.wait_for_input()def use_potion_in_battle(self):"""在战斗中使用药水"""potions = [(i, item) for i, item in enumerate(self.player.inventory) if isinstance(item, Potion)]if not potions:self.slow_print("You don't have any potions!")self.enemy_attack()returnprint("\nAvailable Potions:")for i, (idx, potion) in enumerate(potions):print(f"{i+1}. {potion.name} (+{potion.heal_amount} HP)")print(f"{len(potions)+1}. Cancel")try:choice = int(input(f"\nSelect a potion (1-{len(potions)+1}): "))if 1 <= choice <= len(potions):idx = potions[choice-1][0]if self.player.use_potion(idx):# 使用药水后敌人仍然会攻击self.enemy_attack()elif choice == len(potions)+1:# 取消使用药水self.battle()else:print("Invalid choice.")self.use_potion_in_battle()except ValueError:print("Please enter a valid number.")self.use_potion_in_battle()def battle_victory(self):"""战斗胜利"""self.clear_screen()self.print_header("VICTORY")self.slow_print(f"You defeated the {self.current_enemy.name}!")# 奖励gold_reward = self.current_enemy.gold_rewardexp_reward = self.current_enemy.exp_rewardself.player.gold += gold_rewardself.slow_print(f"You gained {gold_reward} gold!")self.player.add_exp(exp_reward)# 小概率额外奖励if random.random() < 0.3: # 30% 概率获得物品self.find_item()self.current_enemy = Noneself.state = GameState.PLAYINGself.wait_for_input()def game_over(self):"""游戏结束"""self.clear_screen()self.print_header("GAME OVER")self.slow_print("You have been defeated...", 0.1)self.slow_print(f"\nFinal Stats:")self.slow_print(f"Level: {self.player.level}")self.slow_print(f"Gold collected: {self.player.gold}")self.wait_for_input()self.state = GameState.MAIN_MENUdef rest(self):"""休息恢复生命值"""if self.player.hp == self.player.max_hp:self.slow_print("You are already at full health!")else:heal_amount = int(self.player.max_hp * 0.2) # 恢复20%最大生命值actual_heal = self.player.heal(heal_amount)self.slow_print(f"You rest for a while and recover {actual_heal} HP.")self.wait_for_input()def show_shop(self):"""显示商店界面"""self.clear_screen()self.print_header("SHOP")print(f"Your gold: {self.player.gold}\n")print("Available Items:")for i, item in enumerate(self.shop.inventory):print(f"{i+1}. {item} - {item.value} gold")print(f"\n{len(self.shop.inventory)+1}. Sell items")print(f"{len(self.shop.inventory)+2}. Back to main menu")try:choice = int(input(f"\nEnter your choice (1-{len(self.shop.inventory)+2}): "))if 1 <= choice <= len(self.shop.inventory):self.shop.buy_item(self.player, choice-1)self.wait_for_input()elif choice == len(self.shop.inventory)+1:self.sell_items()elif choice == len(self.shop.inventory)+2:self.state = GameState.PLAYINGelse:print("Invalid choice. Please try again.")self.wait_for_input()except ValueError:print("Please enter a valid number.")self.wait_for_input()def sell_items(self):"""出售物品界面"""self.clear_screen()self.print_header("SELL ITEMS")if not self.player.inventory:self.slow_print("You don't have any items to sell!")self.wait_for_input()returnprint(f"Your gold: {self.player.gold}\n")print("Your Items:")for i, item in enumerate(self.player.inventory):equipped = ""if item == self.player.weapon:equipped = " [Equipped Weapon]"elif item == self.player.armor:equipped = " [Equipped Armor]"sell_value = item.value // 2print(f"{i+1}. {item} - Sell for {sell_value} gold{equipped}")print(f"\n{len(self.player.inventory)+1}. Back to shop")try:choice = int(input(f"\nEnter your choice (1-{len(self.player.inventory)+1}): "))if 1 <= choice <= len(self.player.inventory):self.shop.sell_item(self.player, choice-1)self.wait_for_input()self.sell_items() # 返回出售界面elif choice == len(self.player.inventory)+1:return # 返回商店else:print("Invalid choice. Please try again.")self.wait_for_input()self.sell_items()except ValueError:print("Please enter a valid number.")self.wait_for_input()self.sell_items()def show_inventory(self):"""显示库存界面"""self.clear_screen()self.print_header("INVENTORY")if not self.player.inventory:self.slow_print("Your inventory is empty!")self.wait_for_input()self.state = GameState.PLAYINGreturnprint(f"Gold: {self.player.gold}\n")print("Items:")weapons = []armors = []potions = []for i, item in enumerate(self.player.inventory):equipped = ""if item == self.player.weapon:equipped = " [Equipped]"weapons.append((i, item, equipped))elif item == self.player.armor:equipped = " [Equipped]"armors.append((i, item, equipped))elif isinstance(item, Weapon):weapons.append((i, item, equipped))elif isinstance(item, Armor):armors.append((i, item, equipped))elif isinstance(item, Potion):potions.append((i, item, equipped))if weapons:print("\nWeapons:")for i, item, equipped in weapons:print(f"{i+1}. {item}{equipped}")if armors:print("\nArmors:")for i, item, equipped in armors:print(f"{i+1}. {item}{equipped}")if potions:print("\nPotions:")for i, item, equipped in potions:print(f"{i+1}. {item}")print(f"\nActions:")print(f"e. Equip item")print(f"u. Use item")print(f"b. Back to main menu")choice = input("\nEnter your choice: ").lower()if choice == 'e':self.equip_item()elif choice == 'u':self.use_item()elif choice == 'b':self.state = GameState.PLAYINGelse:print("Invalid choice. Please try again.")self.wait_for_input()def equip_item(self):"""装备物品界面"""self.clear_screen()self.print_header("EQUIP ITEM")equipment = [(i, item) for i, item in enumerate(self.player.inventory) if isinstance(item, Weapon) or isinstance(item, Armor)]if not equipment:self.slow_print("You don't have any equipment to equip!")self.wait_for_input()returnprint("Available Equipment:")for i, (idx, item) in enumerate(equipment):equipped = ""if item == self.player.weapon or item == self.player.armor:equipped = " [Equipped]"print(f"{i+1}. {item}{equipped}")print(f"\n{len(equipment)+1}. Cancel")try:choice = int(input(f"\nSelect equipment to equip (1-{len(equipment)+1}): "))if 1 <= choice <= len(equipment):idx = equipment[choice-1][0]item = self.player.inventory[idx]if isinstance(item, Weapon):self.player.equip_weapon(idx)elif isinstance(item, Armor):self.player.equip_armor(idx)self.wait_for_input()elif choice == len(equipment)+1:returnelse:print("Invalid choice. Please try again.")self.wait_for_input()self.equip_item()except ValueError:print("Please enter a valid number.")self.wait_for_input()self.equip_item()def use_item(self):"""使用物品界面"""self.clear_screen()self.print_header("USE ITEM")usable_items = [(i, item) for i, item in enumerate(self.player.inventory) if isinstance(item, Potion)]if not usable_items:self.slow_print("You don't have any usable items!")self.wait_for_input()returnprint("Usable Items:")for i, (idx, item) in enumerate(usable_items):print(f"{i+1}. {item}")print(f"\n{len(usable_items)+1}. Cancel")try:choice = int(input(f"\nSelect item to use (1-{len(usable_items)+1}): "))if 1 <= choice <= len(usable_items):idx = usable_items[choice-1][0]self.player.use_potion(idx)self.wait_for_input()elif choice == len(usable_items)+1:returnelse:print("Invalid choice. Please try again.")self.wait_for_input()self.use_item()except ValueError:print("Please enter a valid number.")self.wait_for_input()self.use_item()def run(self):"""运行游戏主循环"""while self.state != GameState.QUIT:if self.state == GameState.MAIN_MENU:self.show_main_menu()elif self.state == GameState.PLAYING:self.show_game_menu()elif self.state == GameState.BATTLE:self.battle()elif self.state == GameState.SHOP:self.show_shop()elif self.state == GameState.INVENTORY:self.show_inventory()elif self.state == GameState.GAME_OVER:self.game_over()self.clear_screen()self.slow_print("Thank you for playing Dungeon Adventure!", 0.05)self.slow_print("Goodbye!", 0.05)# 运行游戏
if __name__ == "__main__":game = Game()game.run()
4.创建一个自定义容器
# 自定义容器类实现class MultiContainer:"""一个多功能容器类,结合了列表和字典的特性可以通过索引或键来访问元素"""def __init__(self, items=None):# 内部存储结构self._list_data = [] # 按顺序存储元素self._dict_data = {} # 通过键存储元素self._key_index_map = {} # 映射键到索引# 初始化数据if items:if isinstance(items, dict):for key, value in items.items():self.add(value, key)elif isinstance(items, (list, tuple)):for item in items:self.add(item)def add(self, item, key=None):"""添加元素到容器如果提供了key,则可以通过key访问否则只能通过索引访问"""index = len(self._list_data)self._list_data.append(item)if key is not None:if key in self._dict_data:# 如果键已存在,更新对应的值和索引old_index = self._key_index_map[key]self._dict_data[key] = itemself._key_index_map[key] = index# 注意:这会导致旧索引位置的值被覆盖,但在列表中仍然保留else:# 添加新键值对self._dict_data[key] = itemself._key_index_map[key] = indexreturn indexdef remove(self, key_or_index):"""从容器中移除元素可以通过键或索引移除"""if isinstance(key_or_index, int):# 通过索引移除if 0 <= key_or_index < len(self._list_data):# 找到对应的键(如果存在)并从字典中移除keys_to_remove = []for key, idx in self._key_index_map.items():if idx == key_or_index:keys_to_remove.append(key)elif idx > key_or_index:# 更新大于被删除索引的索引映射self._key_index_map[key] = idx - 1for key in keys_to_remove:del self._dict_data[key]del self._key_index_map[key]# 从列表中移除self._list_data.pop(key_or_index)return Truereturn Falseelse:# 通过键移除if key_or_index in self._dict_data:index = self._key_index_map[key_or_index]del self._dict_data[key_or_index]del self._key_index_map[key_or_index]# 从列表中移除self._list_data.pop(index)# 更新所有大于index的索引映射for key, idx in self._key_index_map.items():if idx > index:self._key_index_map[key] = idx - 1return Truereturn Falsedef __getitem__(self, key_or_index):"""实现 container[key] 或 container[index] 语法"""if isinstance(key_or_index, int):# 通过索引访问if 0 <= key_or_index < len(self._list_data):return self._list_data[key_or_index]raise IndexError("Index out of range")else:# 通过键访问if key_or_index in self._dict_data:return self._dict_data[key_or_index]raise KeyError(f"Key '{key_or_index}' not found")def __setitem__(self, key_or_index, value):"""实现 container[key] = value 或 container[index] = value 语法"""if isinstance(key_or_index, int):# 通过索引设置if 0 <= key_or_index < len(self._list_data):# 更新列表中的值self._list_data[key_or_index] = value# 更新字典中对应索引的值(如果有)for key, idx in self._key_index_map.items():if idx == key_or_index:self._dict_data[key] = valuereturnraise IndexError("Index out of range")else:# 通过键设置if key_or_index in self._dict_data:# 更新现有键的值index = self._key_index_map[key_or_index]self._dict_data[key_or_index] = valueself._list_data[index] = valueelse:# 添加新键值对self.add(value, key_or_index)def __delitem__(self, key_or_index):"""实现 del container[key] 或 del container[index] 语法"""if not self.remove(key_or_index):if isinstance(key_or_index, int):raise IndexError("Index out of range")else:raise KeyError(f"Key '{key_or_index}' not found")def __contains__(self, item_or_key):"""实现 item in container 或 key in container 语法"""# 先检查是否为键if item_or_key in self._dict_data:return True# 再检查是否为值return item_or_key in self._list_datadef __len__(self):"""实现 len(container) 语法"""return len(self._list_data)def __iter__(self):"""实现迭代器协议,允许 for item in container 语法默认按列表顺序迭代"""return iter(self._list_data)def items(self):"""返回所有键值对,类似字典的 items() 方法"""return self._dict_data.items()def keys(self):"""返回所有键,类似字典的 keys() 方法"""return self._dict_data.keys()def values(self):"""返回所有值,类似字典的 values() 方法注意:这与直接迭代容器不同,这只返回有键的值"""return self._dict_data.values()def get(self, key, default=None):"""通过键获取值,如果键不存在则返回默认值类似字典的 get() 方法"""return self._dict_data.get(key, default)def get_by_index(self, index, default=None):"""通过索引获取值,如果索引不存在则返回默认值"""if 0 <= index < len(self._list_data):return self._list_data[index]return defaultdef get_index(self, key):"""获取键对应的索引"""if key in self._key_index_map:return self._key_index_map[key]raise KeyError(f"Key '{key}' not found")def get_key(self, index):"""获取索引对应的键(如果有)"""for key, idx in self._key_index_map.items():if idx == index:return keyreturn Nonedef pop(self, key_or_index, default=None):"""移除并返回指定键或索引的元素如果不存在,返回默认值"""try:value = self[key_or_index]self.remove(key_or_index)return valueexcept (KeyError, IndexError):if default is not None:return defaultraisedef clear(self):"""清空容器"""self._list_data.clear()self._dict_data.clear()self._key_index_map.clear()def update(self, other):"""使用另一个容器或字典更新当前容器"""if isinstance(other, MultiContainer):for key, value in other.items():self[key] = value# 添加没有键的元素for i, item in enumerate(other):if other.get_key(i) is None:self.add(item)elif isinstance(other, dict):for key, value in other.items():self[key] = valueelif isinstance(other, (list, tuple)):for item in other:self.add(item)def __str__(self):"""字符串表示"""list_repr = str(self._list_data)dict_repr = str({k: self._dict_data[k] for k in self._dict_data})return f"MultiContainer(list={list_repr}, dict={dict_repr})"def __repr__(self):return self.__str__()# 测试代码
if __name__ == "__main__":# 创建一个空容器container = MultiContainer()# 添加元素container.add("apple") # 只能通过索引访问container.add("banana", "yellow_fruit") # 可以通过键"yellow_fruit"或索引1访问container.add("cherry", "red_fruit")print("Container after adding elements:", container)# 通过索引访问print("\nAccessing by index:")print("container[0]:", container[0])print("container[1]:", container[1])# 通过键访问print("\nAccessing by key:")print("container['yellow_fruit']:", container["yellow_fruit"])print("container['red_fruit']:", container["red_fruit"])# 修改元素container[0] = "green_apple"container["yellow_fruit"] = "ripe_banana"print("\nContainer after modifying elements:", container)# 使用get方法print("\nUsing get methods:")print("container.get('yellow_fruit'):", container.get("yellow_fruit"))print("container.get('missing_key', 'default'):", container.get("missing_key", "default"))print("container.get_by_index(0):", container.get_by_index(0))# 检查成员关系print("\nMembership tests:")print("'green_apple' in container:", "green_apple" in container)print("'yellow_fruit' in container:", "yellow_fruit" in container)print("'orange' in container:", "orange" in container)# 长度print("\nLength of container:", len(container))# 迭代print("\nIterating over container:")for item in container:print(f" {item}")# 键和值print("\nKeys:", list(container.keys()))print("Values (with keys):", list(container.values()))print("Items:", list(container.items()))# 索引和键的关系print("\nIndex-key relationships:")for i in range(len(container)):key = container.get_key(i)value = container[i]print(f" Index {i}: Key = {key}, Value = {value}")# 移除元素print("\nRemoving elements:")removed_item = container.pop("yellow_fruit")print(f"Removed 'yellow_fruit': {removed_item}")print("Container after removal:", container)# 更新容器print("\nUpdating container:")container.update({"new_key": "new_value", "red_fruit": "strawberry"})container.update(["orange", "grape"])print("Container after update:", container)# 清空容器container.clear()print("\nContainer after clearing:", container)# 使用字典初始化dict_container = MultiContainer({"a": 1, "b": 2, "c": 3})print("\nContainer initialized with dict:", dict_container)# 使用列表初始化list_container = MultiContainer([10, 20, 30, 40])print("Container initialized with list:", list_container)
相关文章:
Python3:面向对象编程
这里写目录标题 🧩 面向对象编程:让代码化身为积木世界一、核心概念:类与对象二、四大基石:面向对象的核心特性1️⃣ 封装(Encapsulation):包装复杂性,提供简单接口2️⃣ 继承(Inheritance):站在…...
数据可视化 —— 饼图
一、饼图的所有常用使用场景 饼图是一种直观展示数据占比关系的图表,适用于以下常见场景: 1. 市场与商业分析 市场份额:展示不同品牌/产品在市场中的占有率。 收入构成:分析公司各业务线或产品的收入占比。 客户分布࿱…...
OpenLayers WebGL与3D渲染 (进阶一)
1. WebGL概述 WebGL是一种JavaScript API,它基于OpenGL ES 2.0/3.0标准,允许在不使用插件的情况下在兼容的Web浏览器中呈现高性能的交互式3D和2D图形。在地理信息系统(GIS)领域,WebGL为地图渲染和空间数据可视化提供了强大的性能支持。 1.1…...
ARP协议(地址解析协议)
ARP协议是用来把IP地址转换成MAC地址的。 因为在局域网里,真正通信靠的是MAC地址,但我们平时只知道目标的IP地址,所以需要一个办法把IP地址变成MAC地址 —— 这个过程就是靠ARP完成的。 举个超简单的例子: 你电脑要发数据给192.1…...
深度学习常见框架:TensorFlow 与 PyTorch 简介与对比
🐇明明跟你说过:个人主页 🏅个人专栏:《深度探秘:AI界的007》 🏅 🔖行路有良友,便是天堂🔖 目录 一、引言 1、为什么需要深度学习框架? 2、框架的发展背…...
iOS 类与对象底层原理
iOS 类与对象底层原理 文章目录 iOS 类与对象底层原理探索对象本质objc_setProperty 源码cls与类的关联原理联合体isa的类型isa_t 原理探索initIsa方法通过setClass方法中的shiftcls来验证绑定的一个流程通过 isa & ISA_MSAK通过object_getClass通过位运算 类&类的结构…...
Babel、core-js、Loader之间的关系和作用全解析
在现代前端开发中,Babel、polyfill(如 core-js)和 Loader 是非常常见又容易混淆的几个概念。为了彻底搞明白它们的作用、关系和使用方法,下面一篇文章详细梳理。 一、Babel的作用 Babel 是一个 JavaScript 的编译器,主…...
总线位宽不变,有效数据位宽变化的缓存方案
总线位宽不变,有效数据位宽变化的缓存方案 譬如总线位宽为64bit,但是有时候只有高32bit有效,有时只有低32bit有效,有时64bit都有效。总线上收到的数据要先缓存到FIFO中,那么这个FIFO的宽度和深度如何设置呢࿱…...
若依脱敏功能升级:接口返回想脱就脱,想不脱就不脱(实现灵活可控制的数据脱敏)
若依原生框架中的脱敏功能不够灵活(默认超级管理员不脱敏,其他则脱敏)。 有时候,我们有些接口想要脱敏,但是有些接口又不想脱敏。(例如列表查询的时候脱敏。修改的时候,不想数据脱敏࿰…...
【Azure Redis 缓存】在Azure Redis中,如何限制只允许Azure App Service访问?
问题描述 在Azure Redis服务中,如何实现只允许Azure App Service访问呢? 问题解答 Azure Redis 开启 防火墙的功能,并在防火墙中添加上App Service的出口IP地址即可。两步即可实现此目的! 1)查询 App Service 的出口IP…...
如何解决无训练数据问题:一种更为智能化的解决方案
手动标注数据真的很费时间,而且买数据集又贵得要命,还不一定能完全符合你的需求。但这里有个令人兴奋的好消息,为啥不用 AI 来解决这个问题呢? 别再依赖传统方法了,你可以用像 LLM(大型语言模型)和图像生成器这样的 AI 工具,为你的特定目标创建合成训练数据。如今有那…...
AI 应用同质化:一场看不见的资源 “吞噬战”
大家好,我是涛涛,今天聊聊令人担心的事情。 一、同质化的“繁荣”背后 当ChatGPT在2022年掀起全球AI热潮时,中国互联网行业迅速进入“All in AI”模式。根据艾瑞咨询数据,2023年国内AI应用市场新增注册企业超2.3万家,…...
Java + Spring Boot + MyBatis获取以及持久化sql语句的方法
在Java的Spring Boot项目中结合MyBatis获取实际执行的SQL语句,可以通过以下几种方法实现: 方法一:配置MyBatis日志级别 通过调整日志级别,MyBatis会输出执行的SQL语句及参数,适用于快速调试。 修改application.prope…...
「浏览器即OS」:WebVM技术栈如何用Wasm字节码重构冯·诺依曼体系?
一、冯诺依曼架构的维度坍塌 1. 传统计算模型的能量耗散 浏览器执行效率瓶颈分析: 操作x86指令周期Wasm指令周期能效比提升矩阵乘法3894.2x内存访问1234x系统调用120012100x 二、WebVM的量子纠缠架构 1. 浏览器内核的重构 // 基于WASI的系统调用处理 #[no_mangl…...
Vue3项目目录结构规范建议
以下是一个推荐的 Vue 3 项目目录结构规范,适用于中大型项目并遵循最佳实践: 基础目录结构 bash src/ ├─ assets/ # 静态资源 │ ├─ images/ # 图片文件 │ ├─ fonts/ # 字体文件 │ └─ styles/ …...
【计算机视觉】CV实战项目- Four-Flower:基于TensorFlow的花朵分类实战指南
深度解析Four-Flower:基于TensorFlow的花朵分类实战指南 项目概述与技术背景技术栈组成 完整实战流程环境配置1. 基础环境安装2. 项目环境搭建3. 环境验证 数据准备模型架构解析训练过程优化1. 训练配置2. 关键参数建议3. 训练监控 常见问题与解决方案1. 内存不足错…...
4.27 JavaScript核心语法+事件监听
JavaScript负责网页的行为(交互行为) JS基本语法: 引用方式 变量&常量&数据类型: alert()标签输出弹出框,如以上代码会输出true。 函数: 自定义对象: 属性方法行为 JS中的全局变量是window。 js…...
于键值(KV)的表
基于键值(KV)的表 将行编码为键值(KVs) 索引查询:点查询和范围查询 在关系型数据库中,数据被建模为由行和列组成的二维表。用户通过SQL表达他们的意图,而数据库则神奇地提供结果。不那么神奇的…...
Matlab算例运行
1. 使用终端命令运行算例: 2. 如果点击Run 按钮就是会一直报错,所以直接改成终端运行算例...
package.json script 中的 prepare 脚本的作用是什么
在 package.json 的 scripts 中,prepare 脚本是一个特殊的生命周期脚本,主要作用和执行时机如下: prepare 脚本的作用和执行时机 执行时机: 在执行 npm publish 命令之前运行。在执行不带参数的 npm install 命令时运行ÿ…...
图论---最大流(Dinic)
最大流一定是阻塞流,阻塞流不一定是最大流。 阻塞流---从起点到终点的管道已经阻塞了。 时间复杂度: 一般情况:O(n2m)O(n2m)(但实际运行效率较高,尤其在稀疏图上)。 使用当前弧优化后,效率接近…...
FastAPI系列06:FastAPI响应(Response)
FastAPI响应(Response) 1、Response入门2、Response基本操作设置响应体(返回数据)设置状态码设置响应头设置 Cookies 3、响应模型 response_model4、响应类型 response_classResponse派生类自定义response_class 在“FastAPI系列0…...
双目RealSense系统配置rs_camera.launch----实现D435i自制rosbag数据集到离线场景的slam建图
引言 Intel RealSense系列相机因其出色的深度感知能力和灵活的配置选项,在机器视觉与应用中得到广泛应用。大家在后期的slam学习中,无论是对算法本身的性能要求还是实验的泛化性都有一定的要求,那么公开的数据集如kitti、tum、Eourc不能满足…...
【MCP-2】MCP是什么,利用智普大模型在MaxKB中调用自己开发的MCP服务
在上一篇【MCP-1】MCP是什么,从DEMO入手文章中我们介绍了MCP是什么、他能干啥,以及简单的Demo示例等,这篇文章我们使用MaxKB这个工具,利用智普大模型,看看MCP到底怎么用。 创建SSE协议的MCP服务 在上篇文章中的Demo是…...
Allegro23.1新功能之如何单独关闭铜皮显示效果操作指导
Allegro23.1新功能之如何单独关闭铜皮显示效果操作指导 Allegro升级到了23.1的时候,支持单独关闭铜皮显示 ,如下图 如何仅关闭shape的显示,单独显示线,具体操作如下 点击setup...
《从分遗产说起:JS 原型与继承详解》
“天天开心就好” 先来讲讲概念: 原型(Prototype) 什么是原型? 原型是 JavaScript 中实现对象间共享属性和方法的机制。每个 JavaScript 对象(除了 null)都有一个内部链接指向另一个对象,这…...
【Part 2安卓原生360°VR播放器开发实战】第二节|基于等距圆柱投影方式实现全景视频渲染
《VR 360全景视频开发》专栏 将带你深入探索从全景视频制作到Unity眼镜端应用开发的全流程技术。专栏内容涵盖安卓原生VR播放器开发、Unity VR视频渲染与手势交互、360全景视频制作与优化,以及高分辨率视频性能优化等实战技巧。 📝 希望通过这个专栏&am…...
Android——RecyclerView
RecyclerView的使用 依赖 implementation("androidx.recyclerview:recyclerview:1.4.0")activity_recyclerview.xml <androidx.recyclerview.widget.RecyclerViewandroid:id"id/rv"android:layout_width"match_parent"android:layout_height…...
跨域问题(Cross-Origin Problem)
跨域问题(Cross-Origin Problem)是浏览器出于安全考虑,对不同源(协议、域名、端口)之间的资源访问进行限制而引发的限制。以下是详细解释: 1. 核心定义 跨域:当一个网页(源A&#x…...
阿里云直接对系统云盘扩容
阿里云直接对系统云盘扩容 登录阿里云控制台,进入ECS实例管理页面,检查目标磁盘的容量是否已更新为扩容后的数值。通过SSH远程连接服务器,使用命令 lsblk 或 fdisk -l 查看当前磁盘分区和容量,确认扩容后的物理磁盘已被系统识别。…...
Java大厂面试突击:从Spring Boot自动配置到Kafka分区策略实战解析
第一轮核心知识 面试官:请解释Spring Boot中自动配置的工作原理并演示如何自定义一个ConfigurationProperties组件? xbhog:自动配置通过EnableAutoConfiguration注解触发,结合当前环境判断(如是否检测到MyBatis依赖&…...
【python】lambda用法(结合例子理解)
目录 lambda 是什么? 为什么叫 lambda? 语法 举例 1. 最简单的 lambda:单个数字处理 2. 用 lambda 排序一组字符串(按照长度排序) 3. 在列表里找出绝对值最小的数字 4. 给 map() 用 lambda 5. 组合使用:筛选出偶数 lambda 和 def 的对比 lambda 适合用在什么地…...
前端Ui设计工具
PS 稿、蓝湖、Sketch 和 Figma 前端 UI 设计工具的对比分析 PS 稿(Adobe Photoshop) 提供精准设计细节:PS 稿能让前端更精准地理解页面布局、元素尺寸、颜色等,通过精确测量和查看信息面板,把握设计元素的空间关系、…...
深入探索Python Pandas:解锁数据分析的无限可能
放在前头 深入探索Python Pandas:解锁数据分析的无限可能 深入探索Python Pandas:解锁数据分析的无限可能 在当今数据驱动的时代,高效且准确地处理和分析数据成为了各个领域的关键需求。而Python作为一门强大且灵活的编程语言,…...
django admin 设置字段不可编辑
在Django中,如果你想让管理员在后台管理界面中无法编辑某个字段,你可以通过在模型的Meta类中设置editable属性为False,或者在admin.py文件中使用readonly_fields属性来实现。 方法1:在模型中使用Meta类设置 你可以在模型的Meta类…...
AI在医疗领域的10大应用:从疾病预测到手术机器人
AI在医疗领域的10大应用:从疾病预测到手术机器人 系统化学习人工智能网站(收藏):https://www.captainbed.cn/flu 文章目录 AI在医疗领域的10大应用:从疾病预测到手术机器人摘要引言1. 医学影像诊断:从静态…...
深入理解 Java 单例模式:从基础到最佳实践
单例(Singleton)模式是 Java 中最基本、最常用的设计模式之一。它确保一个类在任何情况下都只有一个实例,并提供一个全局访问点来获取这个唯一的实例。 一、为什么需要单例模式?(使用场景) 单例模式主要适…...
Rust:安全与性能兼得的现代系统编程语言
一、起源与设计理念 Rust 是由 Mozilla 研究院 Graydon Hoare 于 2006 年发起设计的系统级编程语言,其诞生源于传统系统语言(如 C/C)在内存安全与并发编程方面的缺陷。经过近十年的迭代,Rust 1.0 稳定版于 2015 年正式发布&#…...
AI赋能智慧医疗新范式:小天互连即时通讯打造高效、安全的医疗通讯平台
在医疗行业,高效的信息协作与严格的数据安全不仅直接关系患者诊疗效率,更是医院现代化管理的核心命题。小天互连即时通讯系统通过将智能化功能与医疗场景深度结合,打造出全链路数字化协作平台,有效破解了传统沟通模式的效率瓶颈&a…...
图像生成新势力:GPT-Image-1 与 GPT-4o 在智创聚合 API 的较量
在人工智能领域,图像生成技术正迅速发展,OpenAI 推出的 GPT-Image-1 和 GPT-4o 在图像生成方面展现出了强大的能力。智创聚合 API 平台已支持这两个模型,并且其图片生成 / 编辑工作台支持图片的循环编辑等功能,为用户提供了更便捷…...
如何避免爬虫因Cookie过期导致登录失效
1. Cookie的作用及其过期机制 1.1 什么是Cookie? Cookie是服务器发送到用户浏览器并保存在本地的一小段数据,用于维持用户会话状态。爬虫在模拟登录后,通常需要携带Cookie访问后续页面。 1.2 Cookie为什么会过期? 会话Cookie&…...
集成方案 | Docusign + 甄零科技,赋能企业海外业务高效增长!
本文将详细介绍 Docusign 与甄零科技的集成步骤及其效果,并通过实际应用场景来展示 Docusign 的强大集成能力,以证明 Docusign 集成功能的高效性和实用性。 甄零科技是一家专注于数字化合同管理系统的 SaaS 解决方案提供商,致力于为企业打造“…...
【Arxiv 2025】Single Image Iterative Subject-driven Generation and Editing
文章目录 文章标题作者及研究团队介绍01 在论文所属的研究领域,有哪些待解决的问题或者现有的研究工作仍有哪些不足?02 这篇论文主要解决了什么问题?03 这篇论文解决问题采用的关键解决方案是什么?04 这篇论文的主要贡献是什么&am…...
CoOAG:首个捕捉学术研究兴趣动态演变的数据集
2025-04-24,由西安交通大学基于学术合作网络构建一种新的动态图数据集CoOAG,用于研究动态图中的节点分类问题。该数据集通过捕捉作者研究兴趣的动态变化,为动态图学习领域提供了新的研究方向和测试平台,特别是在标签受限的动态节点…...
决策树随机深林
决策树和随机森林是机器学习中常用的两种模型,以下是对它们的简单介绍: 决策树 - 原理:通过一系列的条件判断对样本进行分类或预测。它由节点(内部节点是属性上的测试,叶节点是类别或值)和边组成࿰…...
Unity 和 Unreal Engine(UE) 两大主流游戏引擎的核心使用方法
以下是 Unity 和 Unreal Engine(UE) 两大主流游戏引擎的核心使用方法和对比分析,帮助开发者快速上手并根据项目需求选择合适工具: 一、Unity 使用指南 1. 安装与配置 安装:从 Unity Hub 下载,选择长期支持…...
Maven 依赖范围(Scope)详解
Maven 依赖范围(Scope)详解 Maven 是一个强大的项目管理工具,广泛用于 Java 开发中构建、管理和部署应用程序。在使用 Maven 构建项目时,我们经常需要引入各种第三方库或框架作为项目的依赖项。通过在 pom.xml 文件中的 <depe…...
博物馆除湿控湿保卫战:M-5J1R 电解除湿科技如何重塑文物守护的未来
在卢浮宫幽深的长廊里,达芬奇的《蒙娜丽莎》正经历着一场看不见的战争——不是来自时间的侵蚀,而是空气中无形的水分子。每一件文物都在与湿度进行着无声的抗争,这场抗争关乎人类文明的延续。湿度,这个看不见的文物杀手࿰…...
消防应急物资智能调用立库:豪越科技助力消防“速战速决”
在消防救援的战场上,时间就是生命,每一秒都关乎着人民群众的生命财产安全。然而,在过去的紧急救援中,应急物资无法及时到位的情况时有发生,成为制约救援效率的关键难题,给救援工作带来了巨大的困境。 想象一…...
机器学习基础理论 - 分类问题评估指标
几个定义:混淆矩阵 TP: True Positives, 表示实际为正例且被分类器判定为正例的样本数FP: False Positives, 表示实际为负例且被分类器判定为正例的样本数FN: False Negatives, 表示实际为正例但被分类器判定为负例的样本数TN: True Negatives, 表示实际为负例且被分类…...