python面向对象练习一

复制代码
假设我们正在开发一个学生管理系统,我们需要创建一个Student类来表示学生对象。
每个学生都有学号、姓名和年龄属性。我们还希望能够打印学生的信息,并在删除学生对象时输出一条提示消息。
要求使用__str__()管理学生信息的打印
要求使用__del__()管理删除学生对象时的提示信息
python 复制代码
class Student(object):
    def __init__(self,number,name,age):
        self.number=number
        self.name=name
        self.age=age

    def __str__(self):
        return f'学号:{self.number},姓名:{self.name},年龄:{self.age}'

    def __del__(self):
        print(f'{self.name}对象已被删除')

student=Student('123456','张三',12)
print(student)
del student
复制代码
定义一个水果类,然后通过水果类,创建苹果对象、橘子对象、西瓜对象并分别添加属性:颜色和价格。
python 复制代码
class Fruit():
    pass


apple=Fruit()
apple.colour='红色'
apple.price='8元/kg'
print(f'苹果的颜色为{apple.colour},苹果的价格为{apple.price}')

orange=Fruit()
orange.colour='红色'
orange.price='5元/kg'
print(f'橘子的颜色为{orange.colour},橘子的价格为{orange.price}')

watermelon=Fruit()
watermelon.colour='红色'
watermelon.price='3元/kg'
print(f'西瓜的颜色为{watermelon.colour},西瓜的价格为{watermelon.price}')
复制代码
请编写一个名为 CoffeeMachine 的类,用于表示咖啡机。该类具有以下属性和方法:
属性:
brand:咖啡机的品牌
water_level:水箱的水位
方法:
init(self, brand, water_level):初始化咖啡机对象,接受品牌和初始水位作为参数
brew_coffee(self):冲泡咖啡,检查水位并输出冲泡咖啡的操作提示信息,每次冲泡水位往下递减1升
refill_water(self, amount):加水到水箱,接受加水量作为参数
check_water_level(self):检查水箱的水位,输出当前水位信息
这个咖啡机类模拟了一个简单的咖啡冲泡系统,其中品牌是公开属性,
可以直接访问和修改,而水位只有咖啡机自己知晓,只能在类的内部访问和修改。
通过提供冲泡咖啡、加水和检查水位等方法来管理咖啡机。
python 复制代码
class CoffeeMachine(object):
    def __init__(self, brand, water_level):
        self.brand = brand
        self.__water_level = water_level

    def brew_coffee(self):
        if self.__water_level > 0:
            self.__water_level -= 1
            print(f"使用{self.brand}咖啡机冲泡了一杯咖啡,当前水位:{self.__water_level}升。")
        else:
            print("咖啡机水箱水位不足,无法冲泡咖啡。")

    def refill_water(self, amount):
        self.__water_level += amount  # 加水到水箱
        print(f"向{self.brand}咖啡机加 {amount}升,当前水位:{self.__water_level}升。")

    def check_water_level(self):
        print(f"{self.brand}咖啡机当前水位:{self.__water_level}升。")


coffeeMachine=CoffeeMachine('九阳',10)
coffeeMachine.brew_coffee()
coffeeMachine.refill_water(10)
coffeeMachine.check_water_level()
相关推荐
码路飞1 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽4 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程8 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪8 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook9 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田21 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python