Reputation: 465
I'm having trouble getting the output I want for my code. I want to test a class and the functions defined in the class. This is my code:
class Book:
# the class constructor
def __init__(self, author, title, book_id):
self.title = title
self.author = author
self.book_id = book_id
def __str__(self):
s = "Books("+self.author+", "+self.title+", "+self.book_id+")"
return s
def __repr__(self):
return str(self)
What I did to try to attempt to test it is this:
>>> author="Dr. Suess"
>>> title="The Cat in the Hat"
>>> book_id="12345"
>>> Book
<class '__main__.Book'>
>>>
the output I get is the last line. I'm probably doing it wrong but I don't know how to test it. If someone can show me that would be great!
Upvotes: 2
Views: 180
Reputation: 2300
When you type Book
into the interpreter, you're getting the actual Book
class' representation as output. __repr__
and __str__
both refer to the instance of a Book
, not to the class itself. So to test this, you have to instantiate a Book
:
>>> b = Book("Dr. Suess", "The Cat in the Hat", "12345")
>>> b
"Books(Dr. Suess, The Cat in the Hat, 12345)"
Remember - a class is like a blueprint for an instance. In this case, Book
defines what it means to be a Book
, but it doesn't actually define an actual Book
object - to do that, you need to make a Book
instance using the code I did.
Upvotes: 2
Reputation: 82470
>>> Book
<class '__main__.Book'>
When one does the above in the console, it does not call the __repr__
method created on instance. Let me explain, Book
is merely a class object, its not an instance, because you have not called any arguments to it, however, if you do call arguments, this is what you get:
>>> from Books import Book
>>> Book
<class Books.Book at 0x027B0AE8>
>>> Book("Hello", "World", '1234')
Books(Hello, World, 1234)
As you can see, because we created an instance of a method, we were able to get the __repr__
to be called.
Upvotes: 0