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

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.
Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant...
Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant to mimic the ArrayList data structure. It will hold an ordered list of items. This list should have a variable size, meaning an arbitrary number of items may be added to the list. Most importantly this class should implement the interface SimpleArrayList provided. Feel free to add as many other functions and methods as needed to your class to accomplish this task. In other...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length and #width. Make sure the variable names match those words. #Both will be floats. # #Rectangle should have a constructor with two required #parameters, one for each of those attributes (length and #width, in that order). # #Rectangle should also have a method called #find_perimeter. find_perimeter should calculate the #perimeter of the rectangle based on the current values for #length and width. # #perimeter...
Create a Class to contain a customer order Create attributes of that class to store Company...
Create a Class to contain a customer order Create attributes of that class to store Company Name, Address and Sales Tax. Create a public property for each of these attributes. Create a class constructor without parameters that initializes the attributes to default values. Create a class constructor with parameters that initializes the attributes to the passed in parameter values. Create a behavior of that class to generate a welcome message that includes the company name. Create a Class to contain...
(Rectangle Class) Create class Rectangle. The class has attributes length and width, each of which defaults...
(Rectangle Class) Create class Rectangle. The class has attributes length and width, each of which defaults to 1. It has read-only properties that calculate the Perimeter and the Area of the rectangle. It has properties for both length and width. The set accessors should verify that length and width are each floating-point numbers greater than 0.0 and less than 20.0. Write an app to test class Rectangle. this is c sharp program please type the whole program.
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
In java: -Create a class named Animal
In java: -Create a class named Animal
Define a class named Document that contains an instance variable of type String named text that...
Define a class named Document that contains an instance variable of type String named text that stores any textual content for the document. Create a method named toString that returns the text field and also include a method to set this value. Next, define a class for Email that is derived from Document and includes instance variables for the sender, recipient, and title of an email message. Implement appropriate set and get methods. The body of the email message should...
The Account class Create a class named Account, which has the following private properties:
in java The Account class Create a class named Account, which has the following private properties: number: long balance: double Create a no-argument constructor that sets the number and balance to zero. Create a two-parameter constructor that takes an account number and balance. First, implement getters and setters: getNumber (), getBalance (), setBalan newBalance). There is no setNumber () once an account is created, its account number cannot change. Now implement these methods: void deposit (double amount) and void withdraw (double amount). For both these methods, if the amount is less than...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT