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()
相关推荐
oqX0Cazj212 小时前
2026超火Go-Zero实战:从架构原理到高并发接口落地,彻底解决接口超时、雪崩问题
开发语言·架构·golang
学会去珍惜12 小时前
C语言简介
c语言·开发语言
思麟呀12 小时前
C++11 核心特性(三):强类型枚举、static_assert 与 std::tuple
开发语言·c++
hoiii18712 小时前
Qt 实现屏幕截图功能
开发语言·qt·命令模式
小白学大数据13 小时前
爬虫性能天花板:asyncio赋能 Aiohttp,并发提速 10 倍
开发语言·爬虫·数据分析
Metaphor69213 小时前
使用 Python 给 PDF 设置背景色或背景图
数据库·python·pdf
凡人叶枫13 小时前
Effective C++ 条款07:为多态基类声明 virtual 析构函数
linux·c语言·开发语言·c++
凡人叶枫13 小时前
Effective C++ 条款10:令 operator= 返回一个 reference to *this
java·linux·服务器·开发语言·c++·effective c++
郝亚军13 小时前
如何让pycharm-2026.1.2顶部菜单栏固定显示在最上端
python