玻璃烟灰缸
2021-07-21 01:31
采纳率: 50%
浏览 51
已结题

python父类继承中缺少位置参数?

在学习父类继承中,调用子类的方法显示missing 1 required positional argument:
代码如下:

# 以上是父类
class IceCreamStand(Restaurant):
    """冰激凌"""
    def __init__(self, restaurant_name, cuisine_type):
        """初始化父类属性"""
        super().__init__(restaurant_name, cuisine_type)
        self.flavors = ['a','b']
    def describe_flavors(self, flavors):
        print('We have following flavors:')
        for flavor in flavors:
            print(f'-{flavor}')
my_icecreamstand = IceCreamStand('蜜雪冰城','奶茶')
my_icecreamstand.describe_flavors()

这是从《到实践中》练习9-6的题
显示结果为:

Traceback (most recent call last):
File "D:\Sublime Text\restaurant.py", line 39, in
print(my_icecreamstand.describe_flavors())
TypeError: describe_flavors() missing 1 required positional argument: 'flavors'

  • 收藏

3条回答 默认 最新

  • 碧池阿蒂拉 2021-07-21 02:39
    已采纳

    因为你的describe_flavors方法中,for flavor in flavors循环 这一句,flavors参数不是IceCreamStand类的属性flavors,而是调用方法时传入的参数
    应该改成

        def describe_flavors(self):
            print('We have following flavors:')
            for flavor in self.flavors:
                print(f'-{flavor}')
    
    已采纳该答案
    打赏 评论
  • Feng-licong 2021-07-21 01:37
    
     def describe_flavors(self, flavors=self.flavors):
    

    试试这样

    打赏 评论
  • 玻璃烟灰缸 2021-07-21 01:37

    子类属性添加了,也实例化了,不知道为什么

    打赏 评论

相关推荐 更多相似问题