Adding a Book Data Class
00:00
So now I’d like you to move on to create a Book
data class. So in your code, create some space, start with the @dataclass
decorator and create a class called Book
.
00:16
And the attributes are book_id
,
00:20
that will be an integer. There will be a title
, which is a string. There will be an author
that is also a string. And let’s add a publisher
, which is also a string.
00:36
We will need a use_product
method. And again, I’m going to copy that in because that’s quite a bit of typing.
00:44
And here is the use_product
method for our book. So similar to the data class for Song
, let’s scroll up just a little bit so you can see the use_product
method in row 11 for Song
, and in row 23 for Book
.
01:00
Again, you start with the start_object
method. In this case, it is now a book as opposed to a song, and therefore from self
we have the book_id
as opposed to the song_id
.
01:13 And then we add three properties as opposed to for the song, there were two properties, but because the product classes have been set up so generically you can add as many properties as you need.
01:25
And that’s four in the case of our book. So a title
, an author
, and finally in row 27, a publisher
.
01:35 So please save that and go to your REPL, and see if that works.
01:40
Then once you have restarted the REPL, you can use your up key to import Song
, serialize
, and Book
. Let’s create a book. So my_book
is a Book
and my_book
needs an id.
01:56
So let’s give it 65. It needs a title, It
by the great Stephen King, and the publisher is Scribner, for example. Then to serialize, I use the exact same interface.
02:16
So I’ll pass my_book
into that and let’s try JSON.
02:24
And here you have it. It
by Stephen King has been serialized to JSON, and we can try XML as well. And there you have it. Now you see how flexible you have made your code.
02:39 A book has a different number of properties and different properties from a song, yet serializing it using your generically and flexibly designed products, only required a few lines of code.
02:52
So that’s it for client objects and products. In the next lesson, you’ll revisit the creator and you will be creating a Creator
class.
Become a Member to join the conversation.