Question

In: Computer Science

Challenge: Documents Description: Create a class in Python 3 named Document that has specified attributes and...

Challenge: Documents

Description: Create a class in Python 3 named Document that has specified attributes and methods for holding the information for a document and write a program to test the class.

Purpose: The purpose of this challenge is to provide experience creating a class and working with OO concepts in Python 3.

Requirements:

Write a class in Python 3 named Document that has the following attributes and methods and is saved in the file Document.py.

Attributes

__title is a hidden attribute used to hold the document's title (which is a string).

__body is a hidden attribute used to hold the text of the document (which is a string).

__author is a hidden attribute used to indicate the document's author (which is a string).

Methods

__init__ is to define the three attributes above and assign their default values.

get_title should return the value of the __title field.

get_body should return the value of the __body field.

get_author should return the value of the __author field.

Document Generator Program

Once you have created the Document class, create another Python file called documentGenerator.py. This program is to use Document.py as a module.

In documentGenerator.py, prompt the user to enter the title, body, and author for a document. Create a new Documentobject instance to store this data. Then, ask the user if they would like to repeat the process. They should be able to create as many Document object instances as they would like.

After the user is done creating documents, the program is to use the object’s accessor methods (get_title, get_body, and get_author) to retrieve the title, body, and author of each document. This information is to be displayed in a nicely formatted way.

THANK YOU! (:

Solutions

Expert Solution

The program is given below. The comments are provided for the better understanding of the logic.

Document.py file

#Document.py class

class Document:
    #The Method to initialise the hidden variables.  This method takes 3 arguments as shown below.
    def __init__(self, title, body, author):
        #assign the arguments to the hidden variables.
        #The variables starting with __ are hidden and can be accessed only within the class.  It cannot be accessed outside the class.
        self.__title = title
        self.__body = body
        self.__author =  author
    
    #The below are 3 getter methods to return the 3 hidden variables to the calling function.
    #Without these methods, it is not possible to access the 3 hidden variables from outside this class.
    def get_title(self):
        return self.__title
        
    def get_body(self):
        return self.__body

    def get_author(self):
        return self.__author        
    
  
  

The program is given below. The comments are provided for the better understanding of the logic.

documentGenerator.py file

#documentGenerator.py class


#The below import statement will import the details in the file "Document.py"
#Please make sure to put both the python in the same directory
import Document

#Declare a list to hold all the Document instances.
#The user can create any number of instances of the Document and it need to be stored.
documentsList = []

#This variable will handle continuing the loop, if the user wants to enter details of another document.
continueEnteringBookDetails = True

#The loop will continue as long as the variable continueEnteringBookDetails is True
#Inside the loop this variable is set to True or False depending on the user input.
while(continueEnteringBookDetails):
    #Read Title, Body and Author from the user.
    bookTitle = input("Enter Document Title: ")
    bookBody = input("Enter Document Body: ")
    bookAuthor = input("Enter Document Author: ")

    #Create a Document instance.
    #All the 3 variables, we got from the user are passed to the Document class.
    #In the Document class, this will invoke the __init__ method.
    doc = Document.Document(bookTitle, bookBody, bookAuthor)
    #After the Document instance is created, add that to the list documentsList.
    documentsList.append(doc)
    
    #Check with the user if he//she wants to continue entering details of another document.
    #Set the variable continueEnteringBookDetails to True or False depending on user's input.
    #That will either exit the loop or continue with the loop.
    userInput = input("\nDo you want to enter details of another document (y/n)? ")
    userInput = userInput.strip().lower()
    if(userInput == "y"):
        continueEnteringBookDetails = True
    else:
        continueEnteringBookDetails = False

#Print the Document Details. 
print("\n***The Document details follows***")        

#Print the Header with fixed width 5, 30, 30 characters respectively.  The less than symbol will align it to the left.
print("{0:<5}".format("S#"), end="")
print("{0:<30}".format("Title"), end="")
print("{0:<30}".format("Author"))

i = 1
#Loop through the documentsList and print details one by one.
for doc in documentsList:
    #Use the same width and print the contents.
    print("{0:<5}".format(i), end="")
    print("{0:<30}".format(doc.get_title()), end="")
    print("{0:<30}".format(doc.get_author()))
    
    #The document body is printed in a separate line as it can span multiple lines.
    print("Document Body:")
    print(doc.get_body())
    
    #print a line after each document details.
    print("")
    
    i = i + 1

Please store both the files in the same directory and then run the python documentGenerator.py. Please indent it correctly as per the screenshot

The screenshots of the code and output are provided below.


Related Solutions

Description: Create a class in Python 3 named Animal that has specified attributes and methods. Purpose:...
Description: Create a class in Python 3 named Animal that has specified attributes and methods. Purpose: The purpose of this challenge is to provide experience creating a class and working with OO concepts in Python 3. Requirements: Write a class in Python 3 named Animal that has the following attributes and methods and is saved in the file Animal.py. Attributes __animal_type is a hidden attribute used to indicate the animal’s type. For example: gecko, walrus, tiger, etc. __name is a...
Challenge: Dog Description: Create a Dog class that contains specified properties and methods. Create an instance...
Challenge: Dog Description: Create a Dog class that contains specified properties and methods. Create an instance of Dog and use its methods. Purpose: This application provides experience with creating classes and instances of objects in C#. Requirements: Project Name: Dog Target Platform: Console Programming Language: C# Documentation: Types and variables (Links to an external site.) (Microsoft) Classes and objects (Links to an external site.) (Microsoft) Enums (Links to an external site.) (Microsoft) Create a class called Dog. Dog is to...
Here is the assignment description. * Create a class named 'Account' having the following private attributes...
Here is the assignment description. * Create a class named 'Account' having the following private attributes int accountNumber; double balance; * Write a constructor with parameters for each of the attributes. * Write another constructorwith one parameter for the accountNumber. * Write getter and setter methods for each of the private attributes. * Write a method void credit(double amount) which adds the given amount to the balance. * Write a method void debit(double amount) which subtracts the given amount from...
In python- Create a class defined for Regression. Class attributes are data points for x, y,...
In python- Create a class defined for Regression. Class attributes are data points for x, y, the slope and the intercept for the regression line. Define an instance method to find the regression line parameters (slope and intercept). Plot all data points on the graph. Plot the regression line on the same plot.
Design and develop a class named Person in Python that contains two data attributes that stores...
Design and develop a class named Person in Python that contains two data attributes that stores the first name and last name of a person and appropriate accessor and mutator methods. Implement a method named __repr__ that outputs the details of a person. Then Design and develop a class named Student that is derived from Person, the __init__ for which should receive first name and last name from the class Person and also assigns values to student id, course, and...
Create a Python program that includes each feature specified below. Comments with a detailed description of...
Create a Python program that includes each feature specified below. Comments with a detailed description of what the program is designed to do in a comment at the beginning of your program. Comments to explain what is happening at each step as well as one in the beginning of your code that has your name and the date the code was created and/or last modified. The use of at least one compound data type (a list, a tuple, or a...
Needs to be done in PYTHON A. Create a Dollar currency class with two integer attributes...
Needs to be done in PYTHON A. Create a Dollar currency class with two integer attributes and one string attribute, all of which are non-public. The int attributes will represent whole part (or currency note value) and fractional part (or currency coin value) such that 100 fractional parts equals 1 whole part. The string attribute will represent the currency name. B. Create a CIS22C Dollar derived/inherited class with one additional non-public double attribute to represent the conversion factor from/to US...
Create a super class named Vehicle, which has the following attributes: VIN, engine size, Year, Speed....
Create a super class named Vehicle, which has the following attributes: VIN, engine size, Year, Speed. Check Add a subclass named Car, which has the following additional attributes: Wheel size, Model, Miles (OOD). Check Add another subclass to the vehicle superclass named Boat which has the following additional attributes: Hours, Gas type, Type (Fishing Boat, Deck boat, bowrider boat), and Check Write a method named DisplayInfo() in your main to display the information of the Vehicle. In this method print...
WRITE IN C++ Create a class named Coord in C++ Class has 3 private data items...
WRITE IN C++ Create a class named Coord in C++ Class has 3 private data items               int xCoord;               int yCoord;               int zCoord; write the setters and getters. They should be inline functions               void setXCoord(int)             void setYCoord(int)            void setZCoord(int)               int getXCoord()                     int getYCoord()                   int getZCoord() write a member function named void display() that displays the data items in the following format      blank line      xCoord is                          ????????      yCoord is                          ????????      zCoord...
USING SQL Create a table named Zones with the attributes and assumptions indicated below. Attributes: the...
USING SQL Create a table named Zones with the attributes and assumptions indicated below. Attributes: the zone ID, the lowest and the highest accepted temperature. Assumptions: the ID will be the primary key and have one or two digits, the temperatures (in Fahrenheit) will be at most two digits and a possible minus sign, none of the temperatures can be NULL. Populate table Zones so that it has the following rows: id lowerTemp higherTemp 2 -50 -40 3 -40 -30...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT