【问题标题】:I don't give it as a string but python treats it as a string我不把它当作一个字符串,但 python 把它当作一个字符串
【发布时间】:2021-05-26 21:55:26
【问题描述】:
 class book():
    def __init__(self,name,author,page,type):
        self.name = name
        self.author = author
        self.page = page
        self.type = type
        print("Book information")
    def __len__(self):
        return self.page
xxx = book("Of mice and men","John Steinbeck",293,"Roman")
print(len(xxx))

这段代码是真的。但是如果我写return "Page : {} ".format(self.page) 而不是return self.page,我会遇到错误。为什么?

Error = TypeError: 'str' 对象不能被解释为整数 enter image description here

【问题讨论】:

标签: python-3.x string integer typeerror


【解决方案1】:

您发布的代码运行良好,但图像中的代码返回一个字符串,而不是 @Axe319 指出的 int。

如果您希望该函数打印该文本,您只需在 __len__() 方法中添加一个打印语句,即

 class book():
    def __init__(self,name,author,page,type):
        self.name = name
        self.author = author
        self.page = page
        self.type = type
        print("Book information")
    def __len__(self):
        print(f"Page {self.page}")
        return self.page

xxx = book("Of mice and men","John Steinbeck",293,"Roman")
print(len(xxx))

虽然不是很好。您还可以添加一个属性 (book_length_str) 来返回您想要的字符串,即

 class book():
    def __init__(self,name,author,page,type):
        self.name = name
        self.author = author
        self.page = page
        self.type = type
        print("Book information")

    def __len__(self):
        print(f"Page {self.page}")
        return self.page
    
    @property
    def book_length_str(self):
       return f"Page {self.page}"
    
xxx = book("Of mice and men","John Steinbeck",293,"Roman")
print(xxx.book_length_str)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多