【问题标题】:Using _str_ method to define a library使用 _str_ 方法定义库
【发布时间】:2020-07-17 22:55:07
【问题描述】:

我正在处理一个 python 练习问题:一个名为 Book 的类已经部分定义。您的任务是完成类定义。 Book 按以下顺序接受两个输入变量,title 和 author,它们是字符串。应该有两个实例变量,标题和作者。您应该为 Book 创建 1 个方法。该方法将是 str 方法。当 book 类的实例被打印出来时,它应该使用以下格式:“Author: {author name here}, Title: {title of book here}。”

我已阅读不同的指南并尝试了以下代码,但仍然收到错误消息。有人可以帮我解释一下我在做什么吗?

输入的代码:

class Book():
    def __init__(self,title, author):
        self.title = title
        self.author = author
    def __str__(self):
        return ("Author:"+self.author,"Title:"+self.title)

Book1 = Book("Pride and Prejudice","Jane Austen")

print(Book1)

错误信息:

TypeError Traceback(最近调用 最后)在() 10 Book1 = Book("傲慢与偏见","简·奥斯汀") 11 ---> 12 张打印(书 1)

TypeError: str 返回非字符串(类型元组)

【问题讨论】:

    标签: python string class methods


    【解决方案1】:

    你的代码

    def __str__(self):
       return ("Author:"+self.author,"Title:"+self.title)
    

    确实返回了一个 2 元组:

    def __str__(self):
       return (
           "Author:"+self.author,
           "Title:"+self.title,
       )
    

    如果您使用的是 Python 3.6+,那么您正在寻找

    def __str__(self):
       return f"Author: {self.author}, Title: {self.title}"
    

    或为了与所有版本兼容,

    def __str__(self):
       return f"Author: %s, Title: %s" % (self.author, self.title)
    

    【讨论】:

    • 感谢您的帮助。如果我使用 Python 3.0 会怎样?你知道它是否与 3.6 中的修复相同吗?
    • 是的。 (对于 Python 2.x,您通常还会定义 __unicode__(),但我们先不谈这个。)
    【解决方案2】:

    你也可以使用:

    def __str__(self):
        return 'Author: {}, Title= {}'.format(self.author, self.title)
    

    【讨论】:

    • 如果您添加了一些上下文来说明为什么建议将其作为答案,您可以为社区改进此答案。在此处阅读有关改进答案的更多信息:stackoverflow.com/help/how-to-answer
    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2018-01-05
    • 2015-12-25
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多