Question

IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand...

IN PYTHON

Assignment Overview

This assignment will give you experience on the use of classes.

Understand the Application

The assignment is to first create a class calledTripleString.TripleStringwill consist of threeinstance attribute strings as its basic data. It will also contain a few instance methods to support that data.

Once defined, we will use it to instantiate TripleString objects that can be used in our main program.

TripleString will contain three member strings as its main data: string1, string2, and string3. We will also add a few class/ static members such as const int MAX_LEN and MIN_LEN. These represents the maximum and minimum length that our class will allow any of its strings to be set to. We can use these static members in the TripleString method whose job it is to test for valid strings (see below).

The Program Spec

Class TripleString Spec Instance Members:

  • (string) string1

  • (string) string2

  • (string) string3

    All legal strings should be between 1 and 50 characters, inclusive.
    As stated in the modules, we never want to see a literal in our methods. So, the class should have static members to hold values for the limits described above, as well as default values for any field that is construct-ed using illegal arguments from the client. These are defined and initialized in the static section.

    Class Static Intended Constants:

  • MIN_LEN = 1

  • MAX_LEN = 50

  • DEFAULT_STRING = "(undefined) "

    Instance Methods
    Default Constructor
    TripleString() -- a default constructor that initializes all members to DEFAULT_STRING. Combination Default/Paramteter-Taking Constructor

    def __init__(self, string1 = DEFAULT_STRING, string2 = DEFAULT_STRING, string3 = DEFAULT_STRING): a constructor that initializes all members according to the passed parameters. It must be sure each string satisfies the class requirement for a member string. It does this, as in the modules, by calling the mutators and taking possible action if a return value is false. If any passed parameter does not pass the test,
    a default string should be stored in that member.

    Mutators/Accessor

    set()s andget()s for these members.Mutators in our course are named using the convention as follows: set_string1(...), set_string3(...), etc. Likewise, with accessors: get_string2(). We need an accessor and mutator for each individual string member, so three pairs of methods in this category. Mutators make use of the helper method valid_string(). When a mutator detects an invalid string, no action should be taken. In that case, mutator returns False and the existing string stored in that member prior to the call remains in that member, not a new default string.

string to_string()– a method that returns a string which contains all the information (three strings) of the TripleString object. This string can be in any format as long as it is understandable and clearly formatted.

Helper Methods

def valid_string(self, the_str): – a helper function that the mutators can use to determine whether a string is legal. This method returns True if the string's length is between MIN_LEN and MAX_LEN (inclusive). It returns False, otherwise. This would normally be defined as a class member method, but since we are just starting to learn about static and class methods, we'll allow it to be an instance method this week.

Where it All Goes

There are now a variety of program elements, so let's review the order in which things appear in your .py file:

  1. class definition(s)

  2. global-scope function definition(s) [You may not need them for this assignment.]

  3. main program

In other words, triple_string.py will look like this:

# ---------------- SOURCE ---------------------------------------- class TripleString:

""" encapsulates a 3-string object """

# intended class constants ------------------------------------ MAX_LEN = 50
...

# constructor method ------------------------------------ def __init__(self,

string1 = DEFAULT_STRING, string2 = DEFAULT_STRING, string3 = DEFAULT_STRING):

...

# mutator ("set") methods ------------------------------- ...

# accessor ("get") methods ------------------------------- ...

# helper methods for entire class ----------------- ...

# ------------- CLIENT --------------------------------------------------

# Create 4 TripleString objects triple_string_num_1 = TripleString() ...

The main program

  1. Instantiate four or more TripleString objects, some of them using the default values, some using

    arguments.

  2. Immediately display all objects.

  3. Mutate one or more members of every object.

  4. Display all objects a second time.

  5. Do two explicit mutator tests. For each, call a mutator in an if/else statement which prints one message

    if the call is successful and a different message if the call fails.

  6. Make two accessor calls to demonstrate that they work.

More:

  • Be sure that all output is descriptive. Use labels to differentiate your output sections and full sentences

    in your mutator/accessor tests.

  • No user input should be done in this program.

    I am not supplying a sample output this week – the above description is adequate.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python Code:

class TripleString:
   """ Encapsulates three string objects """
  
   # Class constants
   MIN_LEN = 1
   MAX_LEN = 50
   DEFAULT_STRING = "(undefined)"
  
   def __init__(self, string1 = DEFAULT_STRING, string2 = DEFAULT_STRING, string3 = DEFAULT_STRING):
       """ Constructor """
       # Calling mutator methods
       if not self.set_string1(string1):
           self.string1 = DEFAULT_STRING; # Storing default string
      
       # Assigning string 2
       if not self.set_string2(string2):
           self.string2 = DEFAULT_STRING; # Storing default string
          
       # Assigning string 3  
       if not self.set_string3(string3):
           self.string3 = DEFAULT_STRING; # Storing default string
          
   # Mutator methods
   def set_string1(self, val):
       """ Assigns if valid value is passed """
       if self.valid_string(val):
           self.string1 = val
           return True
       else:
           return False
          
   def set_string2(self, val):
       """ Assigns if valid value is passed """
       if self.valid_string(val):
           self.string2 = val
           return True
       else:
           return False
      
   def set_string3(self, val):
       """ Assigns if valid value is passed """
       if self.valid_string(val):
           self.string3 = val
           return True
       else:
           return False
          
   # Accessor methods
   def get_string1(self):
       """ Returns the string """
       return self.string1
      
   def get_string2(self):
       """ Returns the string """
       return self.string2
  
   def get_string3(self):
       """ Returns the string """
       return self.string3
      
   def valid_string(self, val):
       """ Validates the string """
       if len(val) >= self.MIN_LEN and len(val) <= self.MAX_LEN:
           return True
       else:
           return False
          
   def to_string(self):
       """ Method that prints the three strings """
       return "\nString1: " + self.get_string1() + " \t String2: " + self.get_string2() + " \t String3: " + self.get_string3();
      
      
# Testing class
def main():
   """ Main function """
   # Creating instances
   ts1 = TripleString("Hello", "Hai", "Bye")
   ts2 = TripleString("Welcome", "World")
   ts3 = TripleString("Nice", "Python", "Programming")
   ts4 = TripleString("Good")
  
   print("\n\n After Assigning: \n");
  
   # Printing values
   print(ts1.to_string())
   print(ts2.to_string())
   print(ts3.to_string())
   print(ts4.to_string())
  
   # Mutating values of objects
   ts1.set_string2("Morning")
   ts2.set_string3("Subject")
   ts3.set_string1("Good")
   ts4.set_string2("Nice")
   ts4.set_string3("Weather")
  
   print("\n\n After Updating: \n");
  
   # Printing values
   print(ts1.to_string())
   print(ts2.to_string())
   print(ts3.to_string())
   print(ts4.to_string())
  
  
   # Testing mutator methods
   if ts1.set_string2("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"):
       print("\n Updated \n")
   else:
       print("\nError!!! Invalid value\n");
      
   if ts4.set_string2("sssaaaaa"):
       print("\n Updated \n")
   else:
       print("\nError!!! Invalid value\n");
      
   # Checking Accessor methods
   print("\n\n String 2 in Object 1: " + ts2.get_string1())
   print("\n String 3 in Object 3: " + ts3.get_string3() + " \n")
  
  
# Calling main function
main()

_____________________________________________________________________________________

Sample Run:

C:\Users\SaiBabu\AppData\Local\Programs\Python\Python35>python d:\Python TripleString.py After Assigning: string1: Hello Stri

Add a comment
Know the answer?
Add Answer to:
IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Overview This assignment will give you experience on the use of classes. Understand the Application Every...

    Overview This assignment will give you experience on the use of classes. Understand the Application Every internet user–perhaps better thought of as an Internet connection–has certain data associated with him/her/it. We will oversimplify this by symbolizing such data with only two fields: a name ("Aristotle") and a globally accessible IP address ("139.12.85.191"). We could enhance these by adding other—sometimes optional, sometimes needed—data (such as a MAC address, port, local IP address, gateway, etc), but we keep things simple and use...

  • JAVA :The following are descriptions of classes that you will create. Think of these as service...

    JAVA :The following are descriptions of classes that you will create. Think of these as service providers. They provide a service to who ever want to use them. You will also write a TestClass with a main() method that fully exercises the classes that you create. To exercise a class, make some instances of the class, and call the methods of the class using these objects. Paste in the output from the test program that demonstrates your classes’ functionality. Testing...

  • Define a class named Payment that contains an instance variable "paymentAmount" (non-static member variable) of type...

    Define a class named Payment that contains an instance variable "paymentAmount" (non-static member variable) of type double that stores the amount of the payment and appropriate accessor (getPaymentAmount() ) and mutator methods. Also create a method named paymentDetails that outputs an English sentence to describe the amount of the payment. Override toString() method to call the paymentDetails() method to print the contents of payment amount and any other details not included in paymentDetails(). Define a class named CashPayment that is...

  • 1a. Create a class named Inventory - Separate declaration from implementation (i.e. Header and CPP files)...

    1a. Create a class named Inventory - Separate declaration from implementation (i.e. Header and CPP files) 1b. Add the following private member variables - a int variable named itemNumber - an int variable named quantity - a double variable named cost - a double variable named totalCost. Total cost is defined as quantity X cost. - updateTotalCost() which takes no arguments and sets the values of the variable totalCost. 1c. Add the following public functions: - Accessor and Mutators for...

  • Java Program Please help me with this. It should be pretty basic and easy but I...

    Java Program Please help me with this. It should be pretty basic and easy but I am struggling with it. Thank you Create a superclass called VacationInstance Variables destination - String budget - double Constructors - default and parameterized to set all instance variables Access and mutator methods budgetBalance method - returns the amount the vacation is under or over budget. Under budget is a positive number and over budget is a negative number. This method will be overwritten in...

  • In C++, Step 1: Implement the Student Class and write a simple main() driver program to...

    In C++, Step 1: Implement the Student Class and write a simple main() driver program to instantiate several objects of this class, populate each object, and display the information for each object. The defintion of the student class should be written in an individual header (i.e. student.h) file and the implementation of the methods of the student class should be written in a corresponding source (i.e. student.cpp) file. Student class - The name of the class should be Student. -...

  • For this lab assignment, you will be writing a few classes that can be used by...

    For this lab assignment, you will be writing a few classes that can be used by an educator to grade multiple choice exams. It will give you experience using some Standard Java Classes (Strings, Lists, Maps), which you will need for future projects. The following are the required classes: Student – a Student object has three private instance variables: lastName, a String; firstName, a String; and average, a double. It has accessor methods for lastName and firstName, and an accessor...

  • Please help with this assignment. Thanks. 1. Write a C++ program containing a class Invoice and...

    Please help with this assignment. Thanks. 1. Write a C++ program containing a class Invoice and a driver program called invoiceDriver.cpp. The class Invoice is used in a hardware store to represent an invoice for an item sold at the store. An invoice class should include the following: A part number of type string A part description of type string A quantity of the item being purchased of type int A price per item of type int A class constructor...

  • Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the...

    Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the concept of a college course, assuming that a course has following attributers: code (for instance COSC1337), a description, and a number of credits (for instance 3). Include a constructor, the accessors, mutators and methods ‘toString’, ‘equals’, and ‘finalize’. Write a client class to test the behavior of the class and its methods. The outline of the class is given as follows: public class Course...

  • Task 01: (a)Write a class Fruit with: private instance variables name, and pricePerKilogram Appropriate constructor Appropriate...

    Task 01: (a)Write a class Fruit with: private instance variables name, and pricePerKilogram Appropriate constructor Appropriate accessor methods Appropriate mutator methods toString method equals method (b) Write a FruitDriver class that: Initializes an array of Fruit objects, fruitArray, with 10 objects with names: banana, apple, mango, orange,pineapple, pear, grapes, tangerine, watermelon, sweetmelon and appropriate prices per kilogram. Uses an appropriate loop to display all objects with pricePerKilogram > 5.00 Saudi Riyals, if any. Calls a linearSearch method:                        public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT