Assignment: CP4 - Classes and Objects

22-23 - HHS - UW CSE163 INT DATA PROG A - T2
2023-01-10T20:03:40Z

Due: Mar 17, 2023 by 11:59pm

Lesson 13 Instructions

This checkpoint exercise comes from:

Lesson 13: Practice: Point Class

Lesson 13: Practice: Student

Complete the following two classes:

Point

Student

Unit tests should pass as usual, but most of the tests are run by the file run_tests.py. These test will also execute when you click the 'Run' button.

Point Class

Define a class Point that represents a 2D point (x, y) in the file point.py.

The Point class should have PRIVATE fields for the x and y coordinates. You need to update the instance fields to be private.

The class sould have the following methods.

An initializer that takes the x and y values.

A public method named get_x that returns the x value of this Point.

A public method named get_y that returns the y value of this Point.

A public method named set_x that takes a new x value and updates this Point‘s x to the parameter.

A public method named set_y that takes a new y value and updates this Point‘s y to the parameter.

A public method named display that returns a str representation of the point. It should return '(x, y)' where x is its x value and y is its y value.

For example, your class should have the following behavior (return value shown in comments). This code is provided for you in point_client.py (which you don’t need to edit).

p = Point(1, 2)
print(p.get_x())    # 1
p.set_y(4)
print(p.display())  # '(1, 4)'

Student Class

Define a class Student that represents a student at UW in the file student.py .

In general you will have to determine which fields your class should have, but for the purpose of testing this practice problem, we will tell you the names and the values they should store. We will not be dealing with private fields. Name the fields exactly as shown below.

name stores the name of the student.

student_number stores the student number of the student.

classes is a dict that stores course names as keys and number of credits as values. The keys will be str and the values should be int .

The Student should have the following methods.

An initializer that takes in the student number, and the name of a file containing information about their schedule (more on this below).

A method named get_name that returns the student’s name.

A method named get_student_number that returns the student’s student number.

A method called get_credits_for that takes a class name and returns the number of credits this student is taking for that class. If the student is not taking the given class, this method should return None .

A method named get_classes that returns a list of the classes the student is taking.

Student Initializer

The initializer for the student should take the parameters described above which includes a file name. Suppose for example that the file nicole.txt stored the contents shown below. You can extract the student’s name as the name of the file without the file type at the end. Her file says that Nicole is taking CSE 163 for 4 credits, PHIL 100 for 4 credits, and CSE 390HA for 1 credit.

CSE163 4
PHIL100 4
CSE390HA 1

You could then construct a Student object for Nicole by calling

nicole = Student(1234567, 'nicole.txt')

To implement this, you will need to recall back to how to read a file in Python so that you can build up this dict . Your algorithm for this should split each line and use casting to turn the second value into an int . You may assume the file will be in this expected format and does not have multiple lines for the same class, but you should not assume anything about the number of lines in the file (it may be empty). If the file is empty, then the classes will be an empty dict.

For tests to pass, you'll need to eliminate any relative paths that precede the filename. For example, 'test/suzie.txt' should result in the name 'suzie'.

Client

In the file main.py, write a runnable program to create some Student objects and print some of their state. Your program should use the main method pattern and all of the steps below can be in the main method.

You should create an object for Pablo (his student number 1551515). Pablo’s schedule file is pablo.txt .

You should create an object for Arlo (her student number 1231231). Arlo’s schedule file is stored in arlo.txt .

On one line for each student, you should use the Student object you made to print the name, student number, and the number of credits they are enrolled in for 'CSE163' . The format is shown below. You should use the functions that you defined on the Student class rather than accessing the fields from your client program directly.

pablo 1551515 None
arlo 1231231 4

Remember, you will need to import the Student class from student.py .

Lesson 14 Instructions Overview

Complete the 2 Practice exercises. These come from:

Lesson 14: Practice: DogPack

Lesson 14: Practice: EdPost

All instructions are provided here and slightly modified to work seamlessly with Replit.com.

All the Unit Tests are written using the Python unittest package. You can choose to run the tests for one specific Practice at a time by updating the .replit file. For example, to run the Dog tests, update .replit to run='python run_dog_tests.py'

To run the code, you can choose to execute the go_dogs_go.py file. (Or the matching file for the specific Practice.)

Ultimately, the built-in ReplIt Unit Tests must succeed. These run the same tests.

Lesson 14 - Go Dogs Go - Instructions

This practice problem has two parts. The first modifies the Dog class we worked on in the lesson last time and the second writes a new class called DogPack that stores multiple Dogs.

All the files have been included in the provided starter code. To run the program update .replit to run_dog_tests.py.

Problem 0: Modify Dog

In the module dog.py we have the Dog class. Rename the name field to make it private! Since you are changing the name of the field, you will need to change how it’s accessed in all methods!

After this change, you'll only partially pass teh dog tests. There is more to do!

Problem 1: Write DogPack

In the module dog_pack.py write a class called DogPack. The DogPack should have a field called dogs (remember to make it private though) that will be of type list. The DogPack should have the following methods:

An initializer that should set up the state of the DogPack. The field for the dogs should start out as the empty list.

Hint: Remember the initializer is just like any other method, except that it has a special method name.

A method named add_dog that takes a Dog as a parameter and adds it to the end list of Dogs in the DogPack.

A method called all_bark that goes to each Dog in the DogPack and has them bark.

For example, after running go_dogs_go.py your program should produce the following output. We first show the relevant part of go_dogs_go for context. Note: You may need to update the .replit to run='python go_dogs_go.py'

pack = DogPack()
pack.add_dog(Dog('Chester'))
pack.add_dog(Dog('Scout'))
pack.add_dog(Dog('Bella'))
pack.all_bark()

output

Chester: Woof
Scout: Woof
Bella: Woof

A Note on Testing

Even though we are asking you to make your fields private, we do a bad thing and access the private fields of your class. This is so we can test your implementation matches our specification. We make this decision for its pedagogical benefit, despite its poor style.

A Note About Naming Convention

Python uses snake_case for almost everything. All your functions, variables, fields, and even file names should use snake_case. The one major exception is class names which should be CapitalCase (where the first letter of each word is capitalized... sometimes called PascalCase). This is why we will call the class DogPack but the file name will be dog_pack.py.

Lesson 14 - EdPost Instructions

The discussion board post in this problem is named EdPost because the CSE 163 at UW used EdStem as the discussion board for the course.

Write a class called EdPost that represents a question on the message board. The EdPost class should have an initializer that takes an argument for each of the 3 fields your class should have.

The name of the post (a str) stored in a field title. This parameter should not have a default value.

The topic of the post (a str) stored in a field tag. This field should have the default value General.

The comments on the post (a list) stored in a field comments. The field should have the default value of an empty list.

Your fields should have the names described above but should be made private.

Your class should have the following methods.

An initializer that takes the parameters to initialize the fields as described above (in that order).

Hint: Remember the initializer is just like any other method, except that it has a special method name.

A method named get_title that returns the title of the post.

A method called get_tag that returns the tag on the post

A method called add_comment that adds a comment (a str) to this post.

A method called display that prints out information about the post the following format (using {value} to be a placeholder for a value). The comments should appear in the order they were added, one on each line. Each comment should be indented by two spaces.

{title} ({tag})
Comments:
{comment 1}
{comment 2}
...

For example, the following main program would produce the following output

post1 = EdPost('Typo in spec?', 'Assignment 1')
post1.add_comment('There was a typo!')
post1.add_comment('And maybe another typo?')

post2 = EdPost("What's Hunter's favorite dog?")
post2.add_comment("There can't be just one!")

post1.display()

print()

post2.display()

Typo in spec? (Assignment 1)
Comments:
  There was a typo!
  And maybe another typo?

What's Hunter's favorite dog? (General)
Comments:
  There can't be just one!

Tip

Many students previously reported difficulty getting the formatting right for this display output. Here is a hint: pay careful attention to the amount of whitespace you are using. It might help to replace spaces with another symbol (e.g., ~) so you can visually inspect the number of spaces you are using.

Lesson 15 - Pair Instructions

Write a class called Pair that stores two values and can be used just like a tuple containing two elements. The class you implement should produce the behavior shown in the code cell below. Define the class in pair.py.

You can assume the client will only access index 0 or 1 for a Pair.

The Pair class should be immutable so that the client can’t change its state. This means all fields should be private and if they try to modify a value in the pair, like in the last line of the code cell below, it should print an error message and do nothing else. Notice that you will still need to define the method to allow the syntax for assignment, but the behavior just prints the error without changing the state of the object.

p1 = Pair(1, 2)
p2 = Pair(3, 4)
p3 = Pair(1, 2)

print(p1 == p2)
print(p1 == p3)

print(p1)

print(p1[0])

p1[0] = 14

Output:

False
True
(1, 2)
1
Error: Pair is immutable!

print(p1[0])

p1[0] = 14

Note: Even though Python would use __str__ to print the object, the tests written look for __repr__.

Here is the table of special methods as shown in lesson 15.

Lesson 13 Instructions

This checkpoint exercise comes from:

Lesson 13: Practice: Point Class

Lesson 13: Practice: Student

Complete the following two classes:

Point

Student

Unit tests should pass as usual, but most of the tests are run by the file run_tests.py. These test will also execute when you click the 'Run' button.

Point Class

Define a class Point that represents a 2D point (x, y) in the file point.py.

The Point class should have PRIVATE fields for the x and y coordinates. You need to update the instance fields to be private.

The class sould have the following methods.

An initializer that takes the x and y values.

A public method named get_x that returns the x value of this Point.

A public method named get_y that returns the y value of this Point.

A public method named set_x that takes a new x value and updates this Point‘s x to the parameter.

A public method named set_y that takes a new y value and updates this Point‘s y to the parameter.

A public method named display that returns a str representation of the point. It should return '(x, y)' where x is its x value and y is its y value.

For example, your class should have the following behavior (return value shown in comments). This code is provided for you in point_client.py (which you don’t need to edit).

p = Point(1, 2)
print(p.get_x())    # 1
p.set_y(4)
print(p.display())  # '(1, 4)'

Student Class

Define a class Student that represents a student at UW in the file student.py .

In general you will have to determine which fields your class should have, but for the purpose of testing this practice problem, we will tell you the names and the values they should store. We will not be dealing with private fields. Name the fields exactly as shown below.

name stores the name of the student.

student_number stores the student number of the student.

classes is a dict that stores course names as keys and number of credits as values. The keys will be str and the values should be int .

The Student should have the following methods.

An initializer that takes in the student number, and the name of a file containing information about their schedule (more on this below).

A method named get_name that returns the student’s name.

A method named get_student_number that returns the student’s student number.

A method called get_credits_for that takes a class name and returns the number of credits this student is taking for that class. If the student is not taking the given class, this method should return None .

A method named get_classes that returns a list of the classes the student is taking.

Student Initializer

The initializer for the student should take the parameters described above which includes a file name. Suppose for example that the file nicole.txt stored the contents shown below. You can extract the student’s name as the name of the file without the file type at the end. Her file says that Nicole is taking CSE 163 for 4 credits, PHIL 100 for 4 credits, and CSE 390HA for 1 credit.

CSE163 4
PHIL100 4
CSE390HA 1

You could then construct a Student object for Nicole by calling

nicole = Student(1234567, 'nicole.txt')

To implement this, you will need to recall back to how to read a file in Python so that you can build up this dict . Your algorithm for this should split each line and use casting to turn the second value into an int . You may assume the file will be in this expected format and does not have multiple lines for the same class, but you should not assume anything about the number of lines in the file (it may be empty). If the file is empty, then the classes will be an empty dict.

For tests to pass, you'll need to eliminate any relative paths that precede the filename. For example, 'test/suzie.txt' should result in the name 'suzie'.

Client

In the file main.py, write a runnable program to create some Student objects and print some of their state. Your program should use the main method pattern and all of the steps below can be in the main method.

You should create an object for Pablo (his student number 1551515). Pablo’s schedule file is pablo.txt .

You should create an object for Arlo (her student number 1231231). Arlo’s schedule file is stored in arlo.txt .

On one line for each student, you should use the Student object you made to print the name, student number, and the number of credits they are enrolled in for 'CSE163' . The format is shown below. You should use the functions that you defined on the Student class rather than accessing the fields from your client program directly.

pablo 1551515 None
arlo 1231231 4

Remember, you will need to import the Student class from student.py .

Lesson 14 Instructions Overview

Complete the 2 Practice exercises. These come from:

Lesson 14: Practice: DogPack

Lesson 14: Practice: EdPost

All instructions are provided here and slightly modified to work seamlessly with Replit.com.

All the Unit Tests are written using the Python unittest package. You can choose to run the tests for one specific Practice at a time by updating the .replit file. For example, to run the Dog tests, update .replit to run='python run_dog_tests.py'

To run the code, you can choose to execute the go_dogs_go.py file. (Or the matching file for the specific Practice.)

Ultimately, the built-in ReplIt Unit Tests must succeed. These run the same tests.

Lesson 14 - Go Dogs Go - Instructions

This practice problem has two parts. The first modifies the Dog class we worked on in the lesson last time and the second writes a new class called DogPack that stores multiple Dogs.

All the files have been included in the provided starter code. To run the program update .replit to run_dog_tests.py.

Problem 0: Modify Dog

In the module dog.py we have the Dog class. Rename the name field to make it private! Since you are changing the name of the field, you will need to change how it’s accessed in all methods!

After this change, you'll only partially pass teh dog tests. There is more to do!

Problem 1: Write DogPack

In the module dog_pack.py write a class called DogPack. The DogPack should have a field called dogs (remember to make it private though) that will be of type list. The DogPack should have the following methods:

An initializer that should set up the state of the DogPack. The field for the dogs should start out as the empty list.

Hint: Remember the initializer is just like any other method, except that it has a special method name.

A method named add_dog that takes a Dog as a parameter and adds it to the end list of Dogs in the DogPack.

A method called all_bark that goes to each Dog in the DogPack and has them bark.

For example, after running go_dogs_go.py your program should produce the following output. We first show the relevant part of go_dogs_go for context. Note: You may need to update the .replit to run='python go_dogs_go.py'

pack = DogPack()
pack.add_dog(Dog('Chester'))
pack.add_dog(Dog('Scout'))
pack.add_dog(Dog('Bella'))
pack.all_bark()

output

Chester: Woof
Scout: Woof
Bella: Woof

A Note on Testing

Even though we are asking you to make your fields private, we do a bad thing and access the private fields of your class. This is so we can test your implementation matches our specification. We make this decision for its pedagogical benefit, despite its poor style.

A Note About Naming Convention

Python uses snake_case for almost everything. All your functions, variables, fields, and even file names should use snake_case. The one major exception is class names which should be CapitalCase (where the first letter of each word is capitalized... sometimes called PascalCase). This is why we will call the class DogPack but the file name will be dog_pack.py.

Lesson 14 - EdPost Instructions

The discussion board post in this problem is named EdPost because the CSE 163 at UW used EdStem as the discussion board for the course.

Write a class called EdPost that represents a question on the message board. The EdPost class should have an initializer that takes an argument for each of the 3 fields your class should have.

The name of the post (a str) stored in a field title. This parameter should not have a default value.

The topic of the post (a str) stored in a field tag. This field should have the default value General.

The comments on the post (a list) stored in a field comments. The field should have the default value of an empty list.

Your fields should have the names described above but should be made private.

Your class should have the following methods.

An initializer that takes the parameters to initialize the fields as described above (in that order).

Hint: Remember the initializer is just like any other method, except that it has a special method name.

A method named get_title that returns the title of the post.

A method called get_tag that returns the tag on the post

A method called add_comment that adds a comment (a str) to this post.

A method called display that prints out information about the post the following format (using {value} to be a placeholder for a value). The comments should appear in the order they were added, one on each line. Each comment should be indented by two spaces.

{title} ({tag})
Comments:
{comment 1}
{comment 2}
...

For example, the following main program would produce the following output

post1 = EdPost('Typo in spec?', 'Assignment 1')
post1.add_comment('There was a typo!')
post1.add_comment('And maybe another typo?')

post2 = EdPost("What's Hunter's favorite dog?")
post2.add_comment("There can't be just one!")

post1.display()

print()

post2.display()

Typo in spec? (Assignment 1)
Comments:
  There was a typo!
  And maybe another typo?

What's Hunter's favorite dog? (General)
Comments:
  There can't be just one!

Tip

Many students previously reported difficulty getting the formatting right for this display output. Here is a hint: pay careful attention to the amount of whitespace you are using. It might help to replace spaces with another symbol (e.g., ~) so you can visually inspect the number of spaces you are using.

Lesson 15 - Pair Instructions

Write a class called Pair that stores two values and can be used just like a tuple containing two elements. The class you implement should produce the behavior shown in the code cell below. Define the class in pair.py.

You can assume the client will only access index 0 or 1 for a Pair.

The Pair class should be immutable so that the client can’t change its state. This means all fields should be private and if they try to modify a value in the pair, like in the last line of the code cell below, it should print an error message and do nothing else. Notice that you will still need to define the method to allow the syntax for assignment, but the behavior just prints the error without changing the state of the object.

p1 = Pair(1, 2)
p2 = Pair(3, 4)
p3 = Pair(1, 2)

print(p1 == p2)
print(p1 == p3)

print(p1)

print(p1[0])

p1[0] = 14

Output:

False
True
(1, 2)
1
Error: Pair is immutable!

print(p1[0])

p1[0] = 14

Note: Even though Python would use __str__ to print the object, the tests written look for __repr__.

Here is the table of special methods as shown in lesson 15.