python - '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'
解决方案
当您使用点运算符调用函数时,您通常会调用该函数,其第一个参数是点运算符之前的内容。这就是我们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()
应该工作。
推荐阅读
- python - 如何修复“ValueError:color kwarg 每个数据集必须有一种颜色。提供了 4 个数据集和 1 种颜色”?
- reactjs - 在目标“FBReactNativeSpec”和“Yoga”之间循环依赖;建筑可能会产生不可靠的结果
- python - ipynb 到 py,将所有带有 name* 的文件移动到文件夹
- symfony - 如何在 Symfony Configuration.php 中定义一组标量数组?
- android - Kotlin Unresolved Reference 和类函数未出现在自动完成选择中
- emscripten - 引擎应该如何评估这段 ASM.js 代码?
- c# - 如何从一个 MVC5 应用程序获取访问令牌到另一个 MVC5 应用程序
- r - 有条件地格式化 Shiny rHandsontable 中的空单元格
- android - Linux、adb 和 Google Pixel 3a - 无连接
- python - 从 Python 服务器发送 JSON