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

总结&问题:

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

相关推荐
用户2519162427111 小时前
Python之语言特点
python
刘立军2 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机5 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机6 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i7 小时前
django中的FBV 和 CBV
python·django
c8i7 小时前
python中的闭包和装饰器
python
这里有鱼汤11 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩21 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python