Python 语法类 __repr__ 方法中 fstring 上的错误 [duplicate]

Python SyntaxError on fstring in the __repr__ method of the class [duplicate]

提问人:Raj 提问时间:7/21/2023 最后编辑:wjandreaRaj 更新时间:7/21/2023 访问量:43

问:

我的代码:

class Book:
    all = []
    def __init__(self, ISBN, title, subject, publisher, language, number_of_pages):
        self.__ISBN = ISBN
        self.__title = title
        self.__subject = subject
        self.__publisher = publisher
        self.__language = language
        self.__number_of_pages = number_of_pages
        self.__authors = []

        Book.all.append(self)

    def __repr__(self):
        return f"Title {self.__title} Subject {self.__subject}"

b = Book(23498723,"this","fiction","penguin","en",196)

错误:

    return f"Title {self.__title} Subject {self.__subject}"
                                                          ^
SyntaxError: invalid syntax

谁能解释为什么这是一个错误?

python-3.x 语法错误 f-string

评论

4赞 mkrieger1 7/21/2023
也许您使用的是比 3.6 更旧的 Python 版本。
2赞 wjandrea 7/21/2023
课程和其他一切似乎都是一条红鲱鱼。如果你的脚本只是 f 字符串,你可能会得到同样的错误。将来,请在最小的可重现示例中隔离问题。

答:

2赞 Revisto 7/21/2023 #1

您的 Python 浏览器不支持“f-strings”。

“Python 3.6 版的发布引入了格式化的字符串文字,简称为 f-strings。”

您可以升级到 python 版本 3.6 或最新版本。 从以下链接下载并使用 python 版本 3.6 或更高版本:https://www.python.org/downloads/release/python-3615/

评论

0赞 Raj 7/21/2023
谢谢,有趣的是,VSCode 选择运行 2.7 而不是我通常使用的 3.9。