为什么这段代码在python 3.4中不起作用?

时间:2015-01-21 20:35:23

标签: python sorting namedtuple

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

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

这是我的代码:

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))

2 个答案:

答案 0 :(得分:1)

您的第一行使用功能注释,要求知道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'是一个字符串常量,当然也没关系。

答案 1 :(得分:0)

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


assert restant_price(RC[1]) == 5.50