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()
相关推荐
Warson_L15 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅15 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅15 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L15 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅16 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L16 小时前
python的类&继承
python
Warson_L16 小时前
类型标注/type annotation
python
ThreeS18 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵20 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏