首页 > 解决方案 > 'list' 对象没有属性,这是为什么呢?

问题描述

我正在尝试通过类参数传入项目列表并调用该方法display_flavors来打印列表。但我收到一个list object has no attribute error.

我已经重写了有效的代码,但我想重写代码以传入列表,而不是调用方法并传递列表参数。可能吗?

# Python script Idea to be implemented which has an error
class IceCreamStand(Restaurant):  # Inherits the Parent Class "Restaurant"
    """Attempt to represent an Ice Cream Stand"""
    def __init__(self, restaurant_name, cuisine_name, flavors):
        """Initialize the attributes of an Ice Cream Stand"""
        super().__init__(restaurant_name, cuisine_name) 
        self.flavors = flavors

    def display_flavors(self):
        """Print all the flavors the Ice Cream Stand offers"""
        print("These are flavors offered in this Ice Cream Stand:")
        for flavor in self.flavors:
            print(flavor.title())

list_of_flavors = ["chocolate", "strawberry", "banana"]
restaurant1 = IceCreamStand("Dairy King", "Dairy and Ice Cream", list_of_flavors)
restaurant1.flavors.display_flavors() 

==================================================== ====================== 重写的代码有效

class IceCreamStand(Restaurant):  # Inherits Parent Class "Restaurant"
     """Attempt to represent an Ice Cream Stand"""
    def __init__(self, restaurant_name, cuisine_name):
        """Initialize the attributes of an Ice Cream Stand"""
        super().__init__(restaurant_name, cuisine_name)

    def display_flavors(self, flavors):
        """Print all the flavors the Ice Cream Stand offers"""
        print("These are flavors offered in this Ice Cream Stand:")
        for flavor in flavors:
            print(flavor.title())

list_of_flavors = ["chocolate", "strawberry", "banana"]
restaurant1 = IceCreamStand("Dairy King", "Dairy and Ice Cream")
restaurant1.display_flavors(list_of_flavors)

==================================================== =======================

AttributeError: 'list' object has no attribute 'display_flavors'

标签: pythonpython-3.xlist

解决方案


当您使用点运算符调用函数时,您通常会调用该函数,其第一个参数是点运算符之前的内容。这就是我们self在类中编写方法时包含的原因,例如display_flavors.

当你这样做

restaurant1.flavors.display_flavors()

然后 Python 尝试在没有其他参数的情况下调用display_flavors()object 上的方法。restaurant1.flavors但是,restaurant1.flavors是一个列表,因此没有一个名为display_flowers(). 因此你的AttributeError.

同时,当你这样做时

restaurant1.display_flavors(list_of_flavors)

您正在调用方法display_flavors()on restaurant1- 这是一个IceCreamStand,并且确实有一个名为 that 的方法。所述方法有两个参数:restaurant1(as self) 和list_of_flavors

所以,在你的第一个例子中做restaurant1.display_flavors()而不是restaurant1.flavors.display_flavors()应该工作。


推荐阅读