【问题标题】:Return a list from within a function从函数中返回一个列表
【发布时间】:2015-05-01 03:05:44
【问题描述】:

我试图在另一个函数中调用我在一个函数中创建的列表,但我收到未定义列表的错误。当我尝试执行 Menu = The_menu() 时,它会在函数内运行 while 循环。当我调用 Restaurant_str 时出现问题

from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone menu')
Dish = namedtuple("Dish", "name price calories")


# Constructor:   r1 = Restaurant('Taillevent', 'French', '01-11-22-33-44',  'Escargots', 23.50)

def Restaurant_str(self: Restaurant) -> str:
    return (
        "Name:     " + self.name + "\n" +
        "Cuisine:  " + self.cuisine + "\n" +
        "Phone:    " + self.phone + "\n" +
        "Menu:  " + Dishlist_display(Menu))

def Restaurant_get_info() -> Restaurant:
    """ Prompt user for fields of Restaurant; create and return.
    """
    return Restaurant(
        input("Please enter the restaurant's name:  "),
        input("Please enter the kind of food served:  "),
        input("Please enter the phone number:  "), The_menu())

def The_menu():
    """ Creates the menu that replaces dish in Restaurant.
    """
    Menu = []
    while True:
        x = input("Please enter the name of a Dish:  ")
        if x == "No more":
            break
        y = float(input("Please enter the price of that Dish:  "))
        z = float(input("Please enter the calorie count of that Dish:  "))
        Menu.append(Dish(x, y, z))
    return Menu


def Dish_str(x:Dish) -> str:
    """ Takes a Dish and returns a string with name, price, and calories   listed.
    """
    return (x.name + " ($" + str(x.price) + "): " + str(x.calories) + " cal")

def Dishlist_display(x:list) -> str:
    """Takes a list of Dishes and returns one large string consisting of the     string representation of each dish followed by a newline character
    """
    dish = ""
    for i in x:
         dish = dish + Dish_str(i) + ("\n")
    return dish

这是回溯,

Traceback (most recent call last):
  File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 193,      in <module>
restaurants()
  File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 15, in  restaurants
    our_rests = handle_commands(our_rests)
  File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 43, in   handle_commands
    print(Collection_str(C))
  File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 128,   in Collection_str
    s = s + Restaurant_str(r)
  File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 76, in   Restaurant_str
    "Menu:  " + Dishlist_display(Menu))
NameError: name 'Menu' is not defined

【问题讨论】:

  • 您应该标记编程语言。这看起来像 Python?
  • 哦,好的,谢谢@user1032613
  • 能否请您复制并粘贴实际的回溯?
  • 你在哪里Dishlist_display(Menu)?如果它在这个函数之外,它不能访问这个函数的局部变量Menu。但是既然你做了一个return Menu,那么大概你把它存储在某个地方,并且可以从某个地方访问它。

标签: python list return


【解决方案1】:

问题是您从Restaurant_str 内部调用Dishlist_display(Menu),但该函数中没有名为Menu 的变量。

你碰巧在另一个函数中有一个同名的局部变量这一事实对你没有任何好处。一旦其他函数返回,该变量就消失了。

您需要做的是获取从The_menu 返回的值并将其沿链从一个函数传递到下一个函数,或者将其存储在任何需要它的人都能找到的地方。

如果您以正常的 OO 风格编写此代码,那么正确的做法是将其存储在 Restaurant 实例的属性中,这些函数都是该实例的成员。如果你真的想用 (non-OCa)ML fake-OO 风格编写笨拙地移植到 Python 中,就像你正在做的那样,正确的做法是将它存储在代表对象的闭包中的非局部变量中。如果你想要一种纯粹的函数式风格,那么正确的做法是将它从一个函数传递到另一个函数。但是您必须做一些事情才能将The_menu 返回的值转换为Restaurant_str 可以访问的东西。

【讨论】:

  • 好的,谢谢,我知道我让这件事变得更复杂了。我会按照你说的去做
  • 让我在这里重申一点——如果它是面向对象的会更好。
  • @Joel:实际上,我怀疑你可以在没有 OO 的情况下设计这个应用程序。更重要的是,如果您确实以 OO 术语进行设计,那么您应该使用 Python 的 OO 功能,而不是尝试从头开始。一旦你开始在方法之外添加self args,就该备份并询问为什么它们不是方法。
【解决方案2】:

您似乎在尝试引用未知变量“Menu”,而不是调用构建菜单的函数。

"Menu:  " + Dishlist_display(Menu))

应该阅读

"Menu:  " + Dishlist_display(The_menu()))

或者,您可以使用 Menu = The_menu() 创建您尝试引用的变量

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多