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()
相关推荐
酷在前行12 分钟前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr82822 分钟前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
MC皮蛋侠客34 分钟前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
Zane19941 小时前
@property 到底是怎么把方法伪装成属性的?一文吃透 property、staticmethod、classmethod
后端·python
qq_316411031 小时前
AI 情感陪伴智能潮玩软硬件一体化开发案例
人工智能·python
废弃的小码农1 小时前
功能测试--Day07--Python编程基础
开发语言·python
zx1154502 小时前
大模型工具调用次数限制
人工智能·python
fengci.2 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
MC皮蛋侠客2 小时前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
程序员zgh2 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++