• python面向对象方式-烤地瓜


    # 以面向对象的方式分析烤地瓜

    # 1. 抽象类,在程序中定义类
    # 定义地瓜类
    # 定义人类

    # 2. 分析地瓜类的成员
    # 2.1 属性: 烤地瓜的状态, 烤地瓜的时间, 佐料列表属性
    # 2.2 方法: 无

    # 3. 分析人类的成员
    # 3.1 属性: 姓名, 烤龄,性别
    # 3.2 方法: 烤地瓜的行为方法,添加佐料方法


    # 人类
    class Person(object):
    def __init__(self, name, age):
    self.name = name
    # 烤龄
    self.age = age

    # 提供烤地瓜的行为方法
    def roast(self, time, roast_sp):
    # 把每次传入的时间,累加到烤地瓜的时间属性上
    roast_sp.roast_time += time
    # 根据烤地瓜的总时间来判断地瓜的状态
    if roast_sp.roast_time > 10:
    roast_sp.roast_status = "烤糊了"
    elif roast_sp.roast_time > 6: # [7,10]
    roast_sp.roast_status = "烤熟了"
    elif roast_sp.roast_time > 3: # [4, 6]
    roast_sp.roast_status = "半生不熟"
    else:
    roast_sp.roast_status = "生的"

    # 添加佐料的方法
    def add_condiment(self, new_condiment, roast_sp):
    roast_sp.condiment_list.append(new_condiment)

    def __str__(self):
    return "姓名: %s 烤龄: %d" % (self.name, self.age)


    # 地瓜类
    class SweetPotato(object):
    def __init__(self):
    # 给地瓜对象添加属性信息
    # 烤地瓜的状态
    self.roast_status = "生的"
    # 烤地瓜的时间, 相当于烤地瓜的总时间
    self.roast_time = 0
    # 佐料列表
    self.condiment_list = []

    def __str__(self):
    # 判断地瓜有没有佐料
    if self.condiment_list:
    # ["番茄酱", "辣椒酱"] => "番茄酱,辣椒酱"
    condiment_list_str = ",".join(self.condiment_list)
    return self.roast_status + "地瓜" + "[" + condiment_list_str + "]"
    else:
    return self.roast_status + "地瓜"


    print("===========准备开始烤地瓜啦===========")
    # 通过类创建一个地瓜对象
    sp = SweetPotato()
    print(sp)
    # 通过类创建一个烤地瓜的师傅
    person = Person("老王", 10)
    print(person)

    print("===========先烤三分钟===========")
    person.roast(3, sp)
    print(sp)
    print("===========再烤三分钟===========")
    person.roast(3, sp)
    print(sp)
    print("===========再烤三分钟===========")
    person.roast(3, sp)
    print(sp)
    print("===========添加佐料===========")
    person.add_condiment("番茄酱", sp)
    person.add_condiment("辣椒酱", sp)

    print(sp)

    # 总结:面向对象要找合适的功能对象,合适方法需要放到合适类里面

    人生苦短,我用python
  • 相关阅读:
    CSS快速入门
    Kafka (一) 核心概念
    软件工程模型
    函数式编程
    spark计算操作整理
    HBase 文件合并
    HBase 数据存储结构
    目的论浅谈
    PHP8的注解
    JS的移入移除
  • 原文地址:https://www.cnblogs.com/niucunguo/p/11919199.html
Copyright © 2020-2023  润新知