Create a file named deserializing.py
from marshmallow import Schema, fields, INCLUDE, EXCLUDE # Install marshmallow latest pre-release version: $ pip install -U marshmallow --pre
class BookSchema(Schema): # Class of type Schema
title = fields.Str(required=True) # Schema property, required
author = fields.Str() # Schema property
description = fields.Str() # Schema property
class Book: # Class of type Regular
def __init__(self, title:str, author:str, description:str): # Object constructor
self.title = title # Class property
self.author = author # Class property
self.description = description # Class property
def display(self) -> dict: # function that returns a dictionary of all the properties in the object
return {"title": self.title, "author": self.author, "description": self.description} # dictionary of all the properties in the object
book_dict = {
"title": "Clean Code",
"author": "Bob Martin",
"description": "A book about writing cleaner code, with examples in Java",
} # input dictionary
book_schema = BookSchema(unknown=EXCLUDE) # Creating Object of BookSchema
book = book_schema.load(book_dict) # passing dictionary to the object of class BookSchema
book_obj = Book(**book) # Creating Object of Book
print(book) # print call load function of book_schema object
print(book_obj) # print book_obj object
print(book_obj.display()) # print call display function of book_obj object
print(book_obj.title) # print title property of book_obj object
print(book_obj.author) # print author property of book_obj object
print(book_obj.description) # print description property of book_obj object
Comments
Post a Comment