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()

总结&问题:

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

相关推荐
zh_xuan几秒前
c++ 类的语法3
开发语言·c++
那雨倾城1 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
belldeep3 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP3 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa5 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸6 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝6 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1186 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song7 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive7 小时前
qtc++ qdebug日志生成
开发语言·c++·qt