为什么这段代码在Python3.4中不能工作?

2024-06-08 02:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

定义一个名为restaurant_price的函数,该函数接受一个参数,即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餐厅的列表。在

^{pr2}$

Tags: 函数代码列表参数定义def错误namedtuple
2条回答
def restaurant_price (resant:Restaurant)-> float:
    return restaurant.price


assert restant_price(RC[1]) == 5.50

第一行使用了一个函数注释,它要求已知Restaurant的定义。直到几行之后才定义namedtupleRestaurant。在

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

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,但是{}是一个字符串常量,这当然很好。在

相关问题 更多 >

    热门问题