Aghazada Jamil
Aghazada Jamil

Reputation: 7

I don't give it as a string but python treats it as a string

 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))

this code is true.but if i write return "Page : {} ".format(self.page) instead of return self.page,i meet error.Why?

Error = TypeError: 'str' object cannot be interpreted as an integer enter image description here

Upvotes: 1

Views: 23

Answers (1)

djvaroli
djvaroli

Reputation: 1383

The code you posted works just fine, but the code in the image returns a string not an int as @Axe319 pointed out.

If you wanted the function to print that text you could just add a print statement in the __len__() method, i.e.

 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))

Though that is not great. You could also add a property (book_length_str) that would return the string you want, i.e.

 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)

Upvotes: 1

Related Questions