【问题标题】:why doesn't this code work in python 3.4?为什么这段代码在 python 3.4 中不起作用?
【发布时间】:2015-03-20 12:14:56
【问题描述】:

定义一个名为 restaurant_price 的函数,该函数接受一个参数,即餐厅,并返回该餐厅价格字段的值。所以定义一个包含几家餐馆的列表

我不断收到餐厅未定义的错误。

这是我的代码:

def restaurant_price (Restaurant:Restaurant)-> float:
    return Restaurant.price

from collections import namedtuple 
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
RC = [
    Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50),
    Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50),
    Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50),
    Restaurant("Jitlada", "Thai", "324-4433", "Paht Woon Sen", 15.50),
    Restaurant("Nola", "New Orleans", "336-4433", "Jambalaya", 5.50),
    Restaurant("Noma", "Modern Danish", "337-4433", "Birch Sap", 35.50),
    Restaurant("Addis Ababa", "Ethiopian", "337-4453", "Yesiga Tibs", 10.50) ]
assert restaurant_price(RC[1]) == 5.50

那么我在第二个问题上需要帮助:编写一系列语句,按照从最便宜到最贵(最好的菜)的顺序打印出餐厅 RC 列表。

print(RC.sort(key=restaurant_price))

【问题讨论】:

  • 欢迎来到 SO!请一次只问一个问题。请添加完整的错误消息及其在代码中的指示位置。
  • @howaboutNO 他的代码对我来说似乎语法不正确。
  • 语法是正确的,请让他参考关于如何发布问题和错误的常见问题解答(但给他一个机会),是的,他的声明顺序不正确。
  • @howaboutNO 那是function annotation
  • 顺便说一句:你可以这样使用namedtuples 吗?我认为fields 必须是可迭代的,所以它必须是['name','cuisine','phone','dish','price']

标签: python sorting namedtuple


【解决方案1】:
def restaurant_price (resant:Restaurant)-> float:
    return restaurant.price


assert restant_price(RC[1]) == 5.50

【讨论】:

    【解决方案2】:

    您的第一行使用了一个函数注释,该注释需要知道Restaurant 的定义。直到几行之后,您才定义您的 namedtuple Restaurant

    要么反转这些行,要么只使用字符串作为函数注释,例如:

    def restaurant_price (Restaurant:'Restaurant')-> float:
        return Restaurant.price
    # note that for style purposes, you shouldn't capitalize that since you're
    #    treating it as an object not a class. Use instead:
    # # def restaurant_price(restaurant:'Restaurant') -> float:
    # #     return restaurant.price
    # note also that this is just operator.attrgetter('price')
    

    这里有一些更详细的信息,因为即使是有经验的 Python 用户似乎也会被函数注释绊倒。

    函数注释描述了被引用的参数,但必须是一个有效的表达式Restaurant 不是有效的 Python 表达式,直到您稍后在代码中定义为 namedtuple,但 'Restaurant' 是一个字符串常量,这当然没问题。

    【讨论】:

    • 我仍然不明白的是,没有断言的注释的意义是什么,或者编译器优化...
    • 这有点像在没有任何软件支持的情况下为某物构建硬件。您可以稍后“加入”自省,尤其是在您的 IDE 等中自动进行。the PEP 在标题 Use Cases 下有更多信息
    • 在我看来,如果一个人可以编写一个 func def restaurant_price (Restaurant: Restaurant) -> float - 然后传递一个完全不同的对象并让它返回一个字符串,那么这是一种自我挫败的清晰度。为什么不至少对使用它们的人强制执行注释?
    • @user3467349 我希望像 pylint 这样的东西 会在你尝试将字符串传递给注释为期望 int 的函数时向你抛出警告。至于为什么核心 Python 编译器在这些情况下不会抛出错误,您必须询问 BDFL :P
    • 好的。你们在改变我的陈述顺序和摆脱大写字母方面很到位。任何人都可以建议如何编写代码:编写一系列语句,按照从最便宜到最贵(最好的菜)的顺序打印出餐厅 RC 列表,它应该使用 sort() 和 key=restaurant_price 作为sort() 的参数。
    猜你喜欢
    • 2020-01-28
    • 2013-03-22
    • 2010-09-18
    相关资源
    最近更新 更多