python-17-零基础自学python-

学习内容:《python编程:从入门到实践》第二版

知识点:

类、子类、继承、调用函数

练习内容:

练习9-6:冰激凌小店

冰激凌小店是一种特殊的餐馆。编写一个名为IceCreamStand的类,让它继承为完成练习9-1或练习9-4而编写的Restaurant类。这两个版本的Restaurant类都可以,挑选你更喜欢的那个即可。添加一个名为flavors的属性,用于存储一个由各种口味的冰激凌组成的列表。编写一个显示这些冰激凌的方法。创建一个IceCreamStand实例,并调用这个方法。

我的代码&运行结果:

python 复制代码
class Restaurant:
    def __init__ (self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        
    def describe_restaurant(self):
        print(f"餐馆名,{self.restaurant_name}")
        print(f"餐馆类型,{self.cuisine_type}\n")
        
    def open_restaurant(self):
        print(f"{self.restaurant_name}正在营业中~\n")

class IceCreamStand(Restaurant):#加上父类
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)
        self.flavors = 5

    def describe_icecream(self):
        print(f"这里有{self.flavors}种口味的冰淇淋,分别是:草莓、巧克力、抹茶、芒果和原味")

icecream1 = IceCreamStand('DQ','冰淇淋店')
icecream1.describe_restaurant()
icecream1.open_restaurant()
icecream1.describe_icecream()

练习

注意点:

1.建立子类时,和父类关联的方法中,需要加self

2.super().这一句注意格式,和不需要加self,

如果出现这样的报错,就是属性的数量不一样了,需要再检查是否有写self之类的。

3.flavor的属性储存一个列表,我没有想好,一开始出现了以下报错:

一个方面是super后面没加(),另一方面是我对照课本后,flavors这个地方一般是数据,且,如果我需要和列表一起打印出来,不知道怎么做,我选择,把flavors作为一个口味总数,print的时候,分别概述不同的口味,我不知道对不对,是不是投机解题了。最后反正是打印出来的。

修改了代码如下,想要缩减flavors =['巧克力','抹茶','草莓','芒果','原味'],都会报错

python 复制代码
class Restaurant:
    def __init__ (self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        
    def describe_restaurant(self):
        print(f"餐馆名,{self.restaurant_name}")
        print(f"餐馆类型,{self.cuisine_type}\n")
        
    def open_restaurant(self):
        print(f"{self.restaurant_name}正在营业中~\n")

class IceCreamStand(Restaurant):
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)#这里加flavors会显示not define
        flavors =['巧克力','抹茶','草莓','芒果','原味']#去掉报错,flavors会显示not define
        self.flavors = flavors

    def describe_icecream(self):
        flavors =['巧克力','抹茶','草莓','芒果','原味']#去掉报错,flavors会显示not define
        for flavor in flavors:
            print(f"这里的口味有{flavor}")

icecream1 = IceCreamStand('DQ','冰淇淋店')
icecream1.describe_restaurant()
icecream1.open_restaurant()
icecream1.describe_icecream()

总结&问题:

问题就是不知道列表这么写,是否合适。

相关推荐
墨尘笔尖6 分钟前
使用子进程实现 C++ 与 Python 交互式控制台
c++·windows·python
码界筑梦坊15 分钟前
74-基于Python的蜜雪冰城门店数据可视化分析系统
python·数据分析·flask·毕业设计
喜欢吃燃面17 分钟前
算法中的链表结构
开发语言·c++·学习·算法
十五年专注C++开发17 分钟前
Fruit框架:C++依赖注入解决方案
开发语言·c++·依赖注入·fruit框架
风亦辰73917 分钟前
从 Hello World 到游戏世界——pygame 快速入门
python·游戏·pygame
Lovely Ruby19 分钟前
七日 Go 的自学笔记 (一)
开发语言·笔记·golang
枫叶丹41 小时前
【Qt开发】多元素类控件(三)-> QTreeWidget
开发语言·数据库·c++·qt
晨非辰1 小时前
【数据结构入坑指南】--《层序分明:堆的实现、排序与TOP-K问题一站式攻克(源码实战)》
c语言·开发语言·数据结构·算法·面试
洲覆1 小时前
Redis 驱动适配 Reactor 模式
开发语言·网络·数据库·redis
fl1768311 小时前
基于matlab实现的DnCNN网络
开发语言·matlab