CISC 120: In Class Programming Lab II 1 Introduction The following programming exercise pertains to the basics of object oriented programming, as we discussed in class last time. You will first use a...

Please follow the instruction on the documents. This is a beginner's class, please do not use advanced methods, only follow the steps in the document.


CISC 120: In Class Programming Lab II 1 Introduction The following programming exercise pertains to the basics of object oriented programming, as we discussed in class last time. You will first use a provided class in a program design to solve a problem, and then you will modify this class to extend its functionality. You will have the entire class period to work on this lab. Once that is over, you will have an additional week to work on it outside of class. Part 1: Implementing a Car-Value Calculator Recall the car value calculator that you worked on in a previous homework assignment. This program accepted user input to define a car, and then cal- culated its value based on the input parameters and a very accurate formula that was not at all invented on the spot. The full code for this applica- tion, prior to any modifications to complete the assignment, is contained in Figure 1. This program is begging for object oriented programming. Examining all of the data used by it, observe that the majority of it pertains to the same thing: a car. We can, then, replace some of the code (including most of the math) within our main program by instead using a custom datatype: one that can be used to represent a car. A simple implementation of this idea is contained in Figure 2. Notice how the code associated with calculating the value of the car, and its age, have been placed inside of this class. This means that, once a Car object has been instantiated, you can easily get these values by calling the appropriate method–no need to worry about the calculations themselves in your main program. Using Constructors Recall from our discussion in class last time that a class, which provides a definition for a type, is simply an abstract description of an entire class of possible objects, which share common characteristics (hence the name). The class, Car provides a general description of many possible cars. In order to use this data type to create a specific car, you must make a call to the type’s constructor. This is a special method, defined within the class as 2 Figure 1: The Car Value Calculator code provided with Assignment 4. # carvalue.py import datetime def main(): print('Welcome to Car Value Calculator') ctrl = '' while ctrl != 'n': ctrl = input('Would you like to enter a car [y/n]? ') if ctrl == 'y': model = input('Enter the car model: ') make = input('Enter the car manufacturer: ') year = int(input('Enter the model year: ')) miles = int(input('Enter the car milage: ')) i_val = float(input('Enter the initial value: ')) # datetime.datetime.now().year will # return the current year, as an integer cur_year = datetime.datetime.now().year age = cur_year - year value = (i_val - (i_val * 0.1 * age)) / (miles / i_val)**0.5 print('Your {} {} {} is worth {}'.format(year, make, model, value)) elif ctrl == 'n': continue else: print('Invalid Input') print('Thank you for using the Car Value Calculator') if __name__ == '__main__': main() 3 Figure 2: A possible implementation of a data type to represent cars. import datetime class Car: # The constructor--used to create new objects of this type def __init__(self, make, model, year, i_val, miles): self.make = make self.model = model self.year = year self.i_val = i_val self.miles = miles def value(self): return (self.i_val - (self.i_val * 0.1 * self.age())) / (self.miles / self.i_val)**0.5 def age(self): return datetime.datetime.now().year - self.year __init__(self, parms), which accepts as arguments the necessary values for the attributes of a car, and creates a specific Car object which has those properties (a process called instantiation). For example, we can use the constructor to create an object to represent a 2019 Ford Focus that cost $25, 000 at the time of purchase and has 5, 000 mile on it. Car('Ford', 'Focus', 2019, 25000, 5000) Accessing Methods and Attributes Now, naturally, creating this object isn’t very useful unless we can use it for something. Just like with every other object we’ve worked with, we will want to assign a name to the car we just made, so that we can use it. This is handled using the same assignment syntax that we’ve used up to now. my_car = Car('Ford', 'Focus', 2019, 25000, 5000) Once this statement has been executed, we can access all the attributes and properties of our car by using the same “dot notation” that we’ve used 4 for accessing stuff contained within a module. To get the make, for example, we could use the following code: my_car.make And, as we’ve defined the age and value as methods of this class, we can likewise access those, my_car.age() These methods, which in the homework were defined with the necessary inputs, here don’t require any additional information. All of the values that they need to operate are already contained within (encapsulated) the car object, put there by the constructor. It is very important to keep track of what “members” of a class are attributes, and what are methods. To access an attribute, you must use the syntax obj_name.attr_name, and to call a method use must use the call operator, obj_name.method_name(args). Question 1 Modify the car value calculator above to use the Car class, as well as any additional functions that you see fit (now might be a good time to extract out the code to get input and build the car to a function). The program should maintain all of the same functionality. To actually get the class into the program, don’t copy/paste the definition into the file. Place this class inside of its own file, and then import it. Re- member that you should not put the .py extension in the import statement. If you’ve saved the class in a file called “car.py”, then the import statement that you use should be, import car as always, taking care to ensure that the file “car.py” is contained within the same directory as the program that you are importing it inside of. There is a copy of this module, called “car.py”, on Moodle that you can download and use, rather than copy/pasting or rewriting the class yourself. 5 Part 2 You can use objects created using a class in the same way as you can use any other object. Recall from previous examples (such as our average.py program), that you can use a list object to use a single name to refer to a large number of objects–such as integers. You can do the same thing with cars. In our program, we ask for new cars in a loop. Why not store all of the cars in a list, instead of just throwing the new car away after each iteration? Recall from a previous lecture that an empty list is created using the following syntax: my_list = [] and that, once created, elements can be added to the list using its my_list.append(new_element) method.1 Question 2 Modify the program to store each of the cars in a list as they are created. Print the information about the car by referencing the object stored in the list in some manner.2 Part 3 Recall that when we first began talking about data types, it was in the context of operators. Specifically, we saw them first when considering the odd situation of '1' + '2' == '12' during an addition program. Given that the behavior of operators in Python appears to be a significant reason for the existence of these types, it stands to reason that we should be able to define the behaviors of these operators for our own, custom types. And, lo! we most certainly can. 1Fun fact! Would it surprise you to know that you can also create an empty list using my_list = list()? In this context, what do you think that the list() function does? 2HINT: the len() function will return the total number of elements in a list. You can use this as a starting point for writing code to access the last element of a list. Just remember that the index of a list element starts counting from 0, but the length starts counting from 1. You’ll need to account for this. 6 In this part, we will define not the + operator, but rather the so-called “rich comparision” operators: ==, <,>, etc. We’ll use these operators to compare two cars to one another. This presents us with two major questions to resolve. 1. How do we want to establish an ordering amongst cars? 2. How do we define the behavior of these operators? The first of these questions is a design one, the second is syntax. Both are important. Defining Operator Behavior We’ll start by discussing the syntax–then turn our attention to the problem itself. As we’ve discussed in class, the behavior of operators upon a class is defined within the class itself, by means of the ”dunders” (also called ”magic methods” or ”special methods”). For example, we saw how the addition operator could be defined by using class Point: ... def __add__(self, other): return Point(self.x + other.x, self.y + other.y) ... Strictly speaking, as these are effectively just normal methods (special names and calling conventions notwithstanding) they can be defined in pretty much any way you choose, and with any return types that you choose. But, because these dunders are used to define operators, there are certain expec- tations on how they ought to behave. Python won’t strictly enforce many of these, but if you violate these conventions you won’t make many friends among your fellow Python programmers. 1. The arithmetic operators must return a new object of the same type as its operands (Point + Point = Point, &c.) 2. Comparison operators must return a boolean. 3. Operators should return a new object, and should not affect the state of any of the operands. 7 4. Binary operators should have only two parameters, the first being self. Unary operators should have only one, which should be called self. Okay, so with all of that out the way, on to comparisons. The comparison operators are all binary–they compare one object with another. Hence the dunders used to define them will have two parameters: self, and other. There are five of these operators in total, defining the operations: equal to, less than, greater than, less than or equal to, greater than or equal to. You must define all of them explicitly: Python won’t automatically, for example, determine less than or equal to. Not even if you’ve already defined both less than AND equal to. The definitions of the methods that you must define are: #
Mar 06, 2021
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here