Python class 练习题中的语法错误

Python syntax error in class practice problem

我正在尝试一些练习题以了解更多关于 Python 中的 classes 的信息,并且在 运行 这段代码中,我在第 11 行遇到语法错误( print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}."))。我一遍又一遍地检查我的代码,但没有成功找到问题的解决方案,我想知道是否有人可以帮助我找出问题所在。我也试过从 class 中删除 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

检查您的 python 版本 f 是为 python 3.6 及更高版本引入的 所以它在 python2

中不起作用

您 运行 使用旧 python 版本:

f-string 在 python >= 3.6 版本上工作 看到鼓舞人心的 python pep498 f-string python2.7

a  = 12345
print(f"python2.7 don't support f-strint {a}")
  File "<stdin>", line 1
    print(f"python2.7 don't support f-strint {a}")
                                                ^
SyntaxError: invalid syntax

python3.8

a = 12345                                                                                                                                                                                          

print(f"but on python >3.6 f-strinf work {a}")                                                                                                                                                     
but on python >3.6 f-strinf work 12345

如果您仍在使用 python2,请将打印语句字符串格式从

更改为
print(f"{restaurant.restaurant_name} serves {restaurant.cuisine_type}.")

print(" {} serves {} " .format(restaurant.restaurant_name,restaurant.cuisine_type))