【发布时间】:2020-08-25 17:42:09
【问题描述】:
我正在尝试一些练习题以了解有关 Python 中的类的更多信息,并且在运行此代码时,我在第 11 行 (print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")) 遇到语法错误。我一遍又一遍地检查我的代码,但没有成功找到解决问题的方法,我想知道是否有人可以帮助我找出问题所在。我也尝试从类中删除describe_restaurant 方法,只保留open_restaurant 方法,我仍然收到语法错误,但现在它在第15行。我试图在另一个上找到这个问题的答案问题论坛,但我找不到任何对我有用的东西。我是一名新手程序员,所以如果我在代码中犯了一个愚蠢的错误,我深表歉意。谢谢!
class Restaurant:
"""A simple attempt to model a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant name and cuisine type attributes."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""Give a brief description of the restaurant."""
print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")
def open_restaurant(self):
"""Display a message that the restaurant is open."""
print(f"{self.restaurant_name} is open!")
restaurant = Restaurant('Hard Rock Cafe', 'American Grub')
print(f"{restaurant.restaurant_name} serves {restaurant.cuisine_type}.")
restaurant.describe_restaurant()
restaurant.open_restaurant()
print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")
^
SyntaxError: invalid syntax
【问题讨论】:
-
你是在 2.7 上运行你的 python 吗?
-
printf语句中字符串前面的“f”字符是什么?
-
f 字符串在 Python 3.6 中引入,您必须运行旧版本。
-
参见文档中的f-string。
-
在文本中,您告诉我们错误发生在“describe_restaurant”方法中,但在您的帖子末尾,您表明错误发生在课堂之外。假设在复制和运行代码时最后一个是正确的,我同意 Thierry 的观点。否则请更正问题。
标签: python class methods instance