CS 9, CS 8, CS 11, CS 10

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Which statement is NOT a description of encapsulation?

A collection of methods through which the objects of the class can be manipulated

Which of the following is NOT a difference between methods and functions?

A function is defined as part of a class definition

What is the value of the variable bankAcct after the following code snippet is executed? bankAcct = BankAccount("Fisher", 1000.00)

A memory location

Which of the following is NOT a true statement regarding object-oriented programming?

A programming style where a program is seen as a list of tasks to perform

What happens if you try to open a file for reading that doesn't exist?

A run-time error occurs because the file will not exist

What is the result of the variable position after the following code snippet is executed? inFile.seek(0) inFile.seek(8, SEEK_CUR) inFile.seek(-3, SEEK_CUR) position = inFile.tell()

5

When reading a file in Python, you must specify two items:

a file name and mode

Which method below would be considered an mutator method?

addItem()

What must be included in the subclass constructor as the first statement?

A call to the superclass constructor

Assume that a line has just been read from a file and stored in a variable named line. The line contains several words, each of which is separated by one or more spaces. Which of the following statements will store a list of all the words in wordList?

wordList = line.split()

In the following code snippet, what does the "w" represent? outfile = open("output.txt", "w")

write

What method(s) can be used to write to a file?

write, print

Consider the following code segment: class Fruit : def __init__(self, name) : . . . class Apple : def __init__self(self, name) : . . . Which statement successfully creates a new Apple object?

x = Apple("McIntosh")

Assume a class exists named Fruit. Which of the follow statements constructs an object of the Fruit class?

x = Fruit()

Given the variable assignment sentence = "", what is the value of len(sentence)?

0

If a Byte consists of 8 Bits, what is the min and max values of one Byte?

0 and 255

What is the definition of a class?

A class describes a set of objects with the same behavior

How many methods are there in the following class? class Person : def getName(self) : return self._name def getSalary(self) : return self._salary def giveRaise(self, howMuch) : self._salary = self._salary + howMuch

3

Which statement best describes the public interface for a class?

A collection of methods through which the objects of the class can be manipulated

Which of the following statements about superclasses and subclasses is true?

A subclass extends a superclass.

Which of the following is true regarding subclasses?

A subclass has no access to private instance variables of its superclass.

Which of the following is true regarding subclasses?

A subclass inherits methods and instance variables from its superclass.

Which of the following statements about abstract methods is true?

An abstract method has a name and parameters, but its implementation is not specified.

In the following code snippet, what happens if the "output.txt" file does not exist? outfile = open("output.txt", "w")

An empty file is created

What is the name of the subclass in the following code segment? class Apple(Fruit) : def getCalories(self) :

Apple

Consider the following class definitions: class Fruit : . . . def getColor(self) : . . . class Apple(Fruit) : . . . Which statement is most correct?

Apple inherits the getColor method from Fruit

What would be the inheritance relationships between classes Apples, Pears, and Fruit?

Apples and Pears inherit from Fruit

When using the process of tracing objects for problem solving, which types of methods update the values of the instance variables?

Both B and C

Which of the following questions should you ask yourself in order to determine if you have named your class properly?

Can I visualize an object of the class?

Before invoking a method on an object, what must be done first?

Construct the object

Which of the following patterns can be used for designing your class to help track of the number of fees charged by a bank?

Counting events

What does the subclass inherit from a superclass?

Data and behavior

Which of the following patterns can be used for designing your class for a train object that drives along a track and keeps track of the distance from the terminus?

Describing the Position of an Object

What is the name of the superclass in the following code segment? class Triceratops(Dinosaur) : def eat(self, what) :

Dinosaur

Which of the following is considered by the text to be the most important consideration when designing a class?

Each class should represent a single concept or object from the problem domain.

Identify the list of superclasses from the list of pairs below: Manager, Employee GraduateStudent, Student BankAccount, CheckingAccount Vehicle, Minivan

Employee, Student, BankAccount, Vehicle

Consider the class Employee: class Employee : def __init__(self, firstName, lastName, employeeId) : self._name = lastName + "," + firstName self._employeeId = employeeId . . . If an object is constructed as: sam = Employee("Sam", "Fisher", 54321) What is the contents of the instance variable _name?

Fisher, Sam

Which statement is correct about the following code segment: class Pizza : . . . class Food(Pizza) : . . .

Food is a subclass of Pizza

Consider classes Oranges, Pears, Apples, Fruit. Which should be the superclass?

Fruit

Which of the following is NOT a step carried out by a tester program?

Identify syntax errors

Which of the following is NOT considered part of unit testing for a class?

Identify syntax errors

What exception is raised by the following code segment? data = ["A", "B", "C", "D"] print(data[4])

IndexError

Given the following class definition, what is printed after executing this code snippet? class PhoneNumber : def __init__(self, lName, phone = "215-555-1212") : self._name = lName self._phone = phone Jones = PhoneNumber("Jones") print(Jones._name, Jones._phone)

Jones 215-555-1212

Which of the following patterns can be used for designing your class to add error checking such as not allowing a blank name for a bank account?

Managing Properties of an Object

What is the role of polymorphism?

Manipulate objects that share a set of tasks, even though the tasks are executed in different ways

What items should be considered when creating the public interface?

Method headers and method comments

Consider the following classes: class Dinosaur : . . . class Triceratops(Dinosaur) : . . . class Pterodactyl(Dinosaur) : . . . Which of the following statements is correct?

Methods in Triceratops can call methods in Dinosaur

To override a superclass method in a subclass, the subclass method ____.

Must use the same method name and the same parameters.

How many constructors can be defined for each class?

Only one may be defined

What type of method is used to extend or replace the functionality of the superclass method?

Overriding method

What term describes the process of manipulating objects that share a set of tasks, even though the tasks are executed in different ways?

Polymorphism

In the following code snippet, what happens if the "output.txt" file already exists? outfile = open("output.txt", "w")

The existing file is emptied

What is the purpose of the self parameter?

Refers to the object on which the method was invoked

According to the textbook, what is the best practice for updating instance variables?

Restrict access to instance variables, only allow updates through methods

Consider the following classes: class Vehicle : def __init__(self, type) : self._type = type def getType(self) : return self._type class LandVehicle(Vehicle) : def __init__(self, type) : super().__init__(type) class Auto(LandVehicle) : def __init__(self, type) : super().__init__(type) What is displayed by the following code segment? x = Auto("Sedan") print(x.getType())

Sedan

When designing a class, what is one of the first tasks that need to be done?

Specifying the public interface

What is the purpose of an object's instance variables?

Store the data required for executing its methods

A class that represents a more specific entity in an inheritance hierarchy is called a/an _______.

Subclass

A class that represents the most general entity in an inheritance hierarchy is called a/an ______.

Superclass

Which of the following is NOT true about objects?

The == and != operators test whether two variables are aliases

Which of the following is NOT true about instance methods for a class?

The accessor and mutator methods are automatically called when an object is created

Which of the following is NOT true about constructors?

The constructor is defined using the special method name __default__

What happens when an object is no longer referenced?

The garbage collector removes the object

Consider the following code snippet: aVehicle = new Auto() aVehicle.moveForward(200) If the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method with the same set of parameters, which statement is correct?

The moveForward method of the Auto class will be executed.

Consider the following code snippet: class Vehicle : . . . def setVehicleAttributes(self) : . . . class Auto(Vehicle) : . . . def setVehicleAttributes(self) : . . . Which of the following statements is correct?

The subclass is overriding a superclass method.

What must a subclass do to modify a private superclass instance variable?

The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable.

Consider the following code snippet: class BankAccount : . . . def deposit(self, amount) : self._transactionCount = self._transactionCount + 1 super().deposit(amount) Which of the following statements is correct?

This method calls a public method in its superclass

Which of the following is a purpose of a method?

To access the instance variables of the object on which it acts

What is the purpose of a constructor?

To define and initialize the instance variables of an object

What is the purpose of using an inheritance hierarchy?

To share common code among the classes

What is the purpose of unit testing?

To verify that a class works correctly in isolation, outside a complete program

Which of the following is NOT a valid exception in Python?

TryError

Suppose you have a class ShoppingList, with instance variables _quantity, _cost, and _itemName, how can you access these variables in your program?

Use a method provided by the ShoppingList class

How do you access instance variables in a method?

Using the self reference

you are creating a class inheritance hierarchy about motor vehicles that will contain classes named Vehicle, Auto, and Motorcycle. Which of the following statements is correct?

Vehicle should be the superclass, while Auto, and Motorcycle should be the subclasses

Consider the following code segment: print("W", end="") try : inFile = open("test.txt", "r") line = inFile.readline() value = int(line) print("X", end="") except IOError : print("Y", end="") except ValueError : print("Z", end="") What output is generated when this program runs if test.txt is not opened successfully?

WY

When is a constructor invoked?

When an object is created

Which of the following statements about inheritance is correct?

You can always use a subclass object in place of a superclass object.

What is the substitution principle?

You can always use a subclass object when a superclass object is expected

Which of the following statements about classes is true?

You can create an object from a concrete class, but not from an abstract class.

What are the values in substrings after the following code snippet? states = "Michigan,Maine,Minnesota,,Montana,Mississippi" substrings = states.split(",")

["Michigan","Maine","Minnesota","","Montana","Mississippi"]

Consider the following code segment: line = "hello world!" parts = line.split() print(parts) What is displayed when this code segment runs?

["hello", "world!"]

The readline method reads text until an end of line symbol is encountered, how is an end of line character represented?

\n

Which name would be best for a private instance variable?

_confidential

Consider the following code segment: class Fruit : _type = "Fruit" def __init__(self, color) : self._color = color What is the name of the class variable?

_type

Consider the following class: class Pet : def makeSound(self) : raise NotImplementedError This class is said to be:

an abstract class

Given the following command line, where are the arguments stored? python program.py -v input.dat

argv list

A program is invoked with the command python program.py -r input.dat output.dat What are the elements of argv?

argv[0]: "program.py" argv[1]: "-r" argv[2]: "input.dat" argv[3]: "output.dat"

In the following code snippet, what is it called when you assign one object to the other? bankAcct = BankAccount("Fisher", 1000.00) bankAcct2 = bankAcct

bankAcct and bankAcct2 are aliases

You have been asked to write a program that involves animals. Some animals are herbivores. Within this program, any animal that is not a herbivore is a carnivore. Which set of class definitions is most appropriate for this program?

class Animal : . . . class Herbivore(Animal) : . . . class Carnivore(Animal) : . . .

Consider a class that represents a hardware device. The device can be in one of two states: Plugged in, or unplugged. Which of the following class definitions is best for this situation?

class Device : PLUGGED_IN = 0 UNPLUGGED = 1 def __init__(self) : . . .

Which of the following statements is used to begin the implementation of a new class named Fruit?

class Fruit :

You are creating a Motorcycle class which is supposed to inherit from the Vehicle class. Which of the following class declaration statements will accomplish this?

class Motorcycle(Vehicle) :

Which set of classes is poorly designed?

class Pizza : . . . class Food(Pizza) : . . . class Apple(Food) : . . .

A class name inside parentheses in the class header indicates a ___________________.

class inherits from a superclass

What method ensures that the output has been written to the disk file?

close()

Which of the following method headers represent a constructor?

def __init__(self) :

Consider the following code segment which constructs two objects of type Fruit: x = Fruit() y = Fruit("Banana", "Yellow") Which constructor header will construct both objects successfully?

def __init__(self, name="", color="") :

Consider the following class which is used to represent a polygon consisting of an arbitrary number of (x, y) points: class Polygon : def __init__(self) : self._x_points = [] self._y_points = [] Which of the following code segments is the correct implementation for the addPoint method that adds another point to the polygon?

def addPoint(self, x, y) : self._x_points.append(x) self._y_points.append(y)

Consider the following class definitions: class Dinosaur : . . . def eat(self, what) : . . . class Triceratops(Dinosaur) : . . . _________________ . . . What statement should be placed in the blank to override the implementation of the eat method?

def eat(self, what) :

Consider the following program: class Dinosaur : def __init__(self, name="dinosaur") : self._name = name def display(self) : print(self._name) class Triceratops(Dinosaur) : def __init__(self) : super().__init__("triceratops") x = Dinosaur() x.display() What is displayed when it executes?

dinosaur

Consider the following code segment: done = False while not done : try : filename = input("Enter the file name: ") inFile = open(filename, "r") ________ except IOError : print("Error: File not found.") It is supposed to keep on prompting the user for file names until the user provides the name of a file that can be opened successfully. What line of code should be placed in the blank to achieve this goal?

done = True

Which method is being overridden in the following code segment? class Dinosaur : def __init__(self) : . . . def getName(self) : . . . def draw(self) : . . . class Triceratops(Dinosaur) : def __init__(self) : . . . def draw(self) : . . .

draw

Consider the following code segment: class Employee : def __init__(self, name) : . . . def getSalary(self) : . . . . . . class Programmer(Employee) : def __init__(self, name) : . . . def writeProgram(self) : . . . Which of the following code segments is not legal?

e = Employee("Bob") e.writeProgram()

To avoid the situation where an exception has no handler which causes the program to terminate, what is the correct try/except statement for this code snippet? try : inputFile = open("lyrics.txt", "r") line = inputFile.readline() process(line) ___________ print("Error.")

except IOError :

What code should be added to the end of the following code segment to ensure that inFile is always closed, even if an exception is thrown in the code represented by . . . ? inFile = open("test.txt", "r") try : line = inFile.readline() . . .

finally : inFile.close()

Suppose the input file contains a person's last name and age as a single line of text separated by a space. Which statement(s) extracts the information correctly?

record = inputFile.readline() data = record.split() name = data[0].rstrip() age = int(data[1])

In the following example, which data is considered instance data? You are assigned the task of writing a program that calculates payroll for a small company. To get started the program should do the following: Add new employees including their first and last name and hourly wage Ask for the number of hours worked Calculate payroll (applying 1.5 for any hours greater than 40) Print a report of all employees' salary for the week, total of all hours and total of all salaries

firstName, lastName, hoursWorked, hourlyWage

Which of the following code segments will display all of the lines in the file object named infile, assuming that it has successfully been opened for reading?

for line in infile : print(line)

What is the name of the method in the following code segment? class Fruit : def getColor(self) : return self._color

getColor

Which method below would be considered an accessor method?

getCount()

Consider the following class: class Counter : def getValue(self) : return self._value def click(self) : self._value = self._value + 1 def unClick(self) : self._value = self._value - 1 def reset(self) : self._value = 0 Which method is an accessor?

getValue

Given the following code snippet, how can you test if they reference the same object? bankAcct2 = bankAcct

if bankAcct is bankAcct2 : print("The variables are aliases")

Which statement determines if the middleInit variable is empty or does not refer to any object?

if middleInit is None : print("No middle initial")

Which of the following statements opens a binary file for reading?

inFile = open("test.dat", "rb")

After executing the following code snippet, what part is the file object? infile = open("input.txt", "r")

infile

Which of the following statements opens a text file for reading?

infile = open("myfile.txt", "r")

Which statement is used to close the file object opened with the following statement? infile = open("test.txt", "r")

infile.close()

Which of the following methods strips specified punctuation from the front or end of each string (s)?

s.strip(".!?;:")

The following program opens test.txt and displays its contents. If nothing is placed in the blank, then the contents of the file is displayed double spaced. What should be placed on the blank so that the contents of the file is displayed without the extra blank lines? infile = open("test.txt", "r") line = infile.readline() while line != "" : _________ print(line) line = infile.readline() infile.close()

line = line.rstrip()

Assume that your program is started with the following command: python myProgram.py -z 100 What will be displayed by the following statement? print(sys.argv[0])

myProgram.py

Consider the following code segment: def mutate(self, newType) : self._type = newType self._mutations = self._mutations + 1 What is the name of the local variable in it:

newType

Assume that you are creating a new Python class named Vehicle, as shown below: class Vehicle : . . . What is Vehicle's superclass?

object

Before accessing a file, the program must:

open the file

Assume that outfile is a file object that has been opened for writing. Which of the following code segments stores Hello World in the file?

outfile.write("Hello\nWorld\n")

Which of the follow code segments could be used to help test the getColor method from the Fruit class?

print(f.getColor()) print("Expected: Yellow")

Naming conventions for Python dictate that instance variables should start with an underscore to represent

private visibility

If a class has an abstract method, what statement is commonly used to ensure the user of the class does not attempt to invoke the method of the superclass?

raise NotImplementedError

In the following code snippet, what does the "r" represent? infile = open("input.txt", "r")

read

Consider the following classes: class Vehicle : def __init__(self, name) : self._name = name class LandVehicle(Vehicle) : def __init__(self, numWheels) : super().__init__("Land Vehicle") ____________________ def getWheels(self) : return self._numWheels What statement should be placed in the blank to complete the constructor for LandVehicle?

self._numWheels = numWheels

Given the following code snippet, what statement completes the code to add several items to one grocery list: def addItems(self, price, quantity, itemName) : for i in range(quantity) : ________________________ def addItem(self, price, itemName) : self._itemCount = self._ItemCount + 1 self._totalPrice = self._totalPrice + price

self.addItem(price, itemName)

When using the readline method, what data type is returned?

string

The following two objects are created from the Counter class: studentCounter, and teacherCounter to represent total students and total teachers respectively. If theCounter class contains an instance variable _num that increases every time the user executes the add method, what is the result of each variable after the following code snippet: studentCounter.add() teacherCounter.add() studentCounter.add()

studentCounter : 2, teacherCounter : 1

When you call a superclass method from a subclass method (without overriding the method), what keyword must replace the self reference?

super

Which reserved word must be used to call a method of a superclass?

super

Assume that you have a class Apple which is a subclass of Fruit. Which statement can be used in Apple's constructor to invoke Fruit's constructor?

super().__init__()

What is wrong with the following code snippet that is suppose to print the contents of the file twice? infile = open("input.txt", "r") for sentence in infile : print(sentence) for sentence in infile : print(sentence)

the file cannot iterate over the file twice without closing and reopening the file

Assume that your program is started with the following command: python myProgram.py the quick brown fox What will be displayed by the following statement? print(sys.argv[5])

the program will raise an exception

Given the following code snippet, identify the subclass and superclass: class ChoiceQuestion(Question) : def __init__(self) : . . .

the subclass is ChoiceQuestion, the superclass is Question

Consider the following program: class Dinosaur : def __init__(self, name="dinosaur") : self._name = name def display(self) : print(self._name) class Triceratops(Dinosaur) : def __init__(self) : super().__init__("triceratops") x = Triceratops() x.display() What is displayed when it executes?

triceratops

Which of the following statements sets x so that it refers to no object at all?

x = None

It is good programming practice to plan for possible exceptions and provide code to handle the exception. Which exception must be handled to prevent a divide by zero logic error?

zeroDivisionError


Kaugnay na mga set ng pag-aaral

1.1 | Definitions of Statistics, Probability, and Key Terms

View Set

Unit 2, Chapter 3, Lessons 3 & 4 Study Guide

View Set

Business Law- Ch. 8, 9, 10, 29, 30, 42

View Set

Satire, Irony, Humor (Terms You Need to Know)

View Set

TestOut PC Pro: 11.4 Shared Folders

View Set

BLAW Chapter 21: forms of business organization

View Set