Class入门操作

原文地址: Class入门操作

Introduction

练习Python基础,实现Class的操作,包括Getters, Setters以及内置函数的重载。

Overview

In this assignment, you will be practicing by creating a set of simple classes. You will create three different Python files; prob1.py will have three small classes, while prob2.py and prob3.py will each have one class a piece. Our test code will import your files, and then use your classes, testing them to see if they work properly.

You should definitely create some test code, for each file, so that you can test your own classes locally! Remember, to implement test code, you must have a main() function, but you must ensure that this main() function doesn't run when your code is imported into our tester program. To do that, use an if statement, like this:

''' docstring docstring docstring '''

... your class ...

def main():
   ... your test code ...

if __name__ == "__main__":
  main()

Sharing Test Code

It takes a while to write up a good library of test code. Let's share our insights! While (of course) you should never share your solutions to the problem with other students, we actively encourage you to share your test code with the class on Piazza. And we actively encourage you to take the test code that other students have posted, and include it into your program!

Of course, we the instructors can't endorse the code that other students might post on Piazza, so you should definitely check to see if it follows the spec. But if it follows the spec, feel free to copy it! More tests are better!

prob1.py - Simple Classes, Getters, Setters

In the file prob1.py, you will write three different classes: Simplest, Rotate, and Band.

class Simplest

Simplest is a trivial object, with three public fields, a,b,c. It has a constructor which takes those three as parameters (in the order a,b,c), and sets the public fields in the object. It has no other methods.

Usage Example

obj = Simplest(10,20,30)
print(obj.a)    # should be 10

class Rotate

Rotate stores three different values, but rorates them, round-robin fashion, when you ask it to. It has the following methods:

__init__(self, first,second,third)

Constructor. It should store the three values in private fields.

get_first(self)
get_second(self)
get_third(self)

Getters, for the three values, as they currently stand. This class does not have any setter methods.

rotate(self)

Rotates the first, second, and third values. The first should move to the end (the third position), and the second and third values should move up.

Usage Example

obj = Rotate("foo", "bar", "baz")
print(obj.get_first())    # should be "foo"
obj.rotate()
print(obj.get_first())    # should be "bar"

class Band

Band represents a musical group. It can contain one singer, one drummer, and any number of guitar players. When the object is created, it will only contain a singer; use getters and setters to update the various band members.

All of the data fields must be private fields.

This class has the following methods:

__init__(self, singer)

Constructor. It should store the singer it is passed, set the drummer to None, and record that the band does not (yet) have any guitar players.

get_singer(self)
set_singer(self, new_singer)
get_drummer(self)
set_drummer(self, new_drummer)

Getters and setters for the singer and drummer. The band can only have one singer, and at most one drummer.

add_guitar(self, new_guitar)
get_guitars(self)

Getter and setter for the guitars. New guitars can be added to the Band, but there is no interface to remove one, once it has been added.

play_music(self)

The band plays some music, based on the members of the band. We represent this by printing various lines of output.

First, the singer sings. The class knows of two special singers, Frank Sinatra and Kurt Cobain. All other singers sound exactly the same. If the singer is "Frank Sinatra", (https://www.youtube.com/watch... then print the following:


Do be do be do

If the singer is "Kurt Cobain", (https://www.youtube.com/watch... then print the following: bargle nawdle zouss
Otherwise, print the following:


La la la

Next, the drummer plays the drums. If the drummer is not None, then print the following:


Bang bang bang!

(Don't print anything if there is no drummer.)
Finally, the guitars play. For each guitar player in the band, print the following:


Strum!

(Yes, you may print several lines of the same thing.)

Usage Example

obj = Band("Elvis Presley")
obj.set_drummer("Chad Smith")
obj.play_music()

prob2.py - __str__(), etc.

In the file prob2.py, you will write a single class Color, which represents an RGB color. It stores the red, green, and blue components of the color as integers; each one is in the range [0,255] (inclusive).

All fields must be private. It has the following methods:

__init__(self, r,g,b)

Constructor. This class should accept values that are too large or too small, but should bound them; that is, any value less than 0 should be set to 0 instead, and any number larger than 255 should be set to 255 instead.

(Since you're doing exactly the same thing three times, you really ought to use a function here!)

__str__(self)
html_hex_color(self)
get_rgb(self)

Instead of getters for the individual colors, this class has three methods that allow you to view the color in different ways. The __str__() method (which, of course, is the method that Python will call if you call str(object) ) returns a string that has the red, green, and blue components (in that order); the complete string looks like this:


rgb(10,20,30)

Hint: If you use a Python format string, with the format() function, it's easy to implement this entire method as a single line of code.
html_hex_color() returns the same information, but encoded the way that colors are often specified on web pages. These start with a hash character (#) and then have 6 hexdecimal characters (0 through 9, A through F). The first two represent the red component of the color, the next two represent the green component, and the last two represent the blue component. For example, if the color is (0,255,64), the proper return value would be:


#00ff40

Hint: You don't need to know how hexdecimal works! If you are using Python's format() function, then use the following format specifier to print an integer as two uppercase hex characters:


{:02X}

Finally, the function get_rgb() simply returns the red, green, blue components as a tuple.

set_standard_color(self, name)

This class does not let you change the colors individually. Instead, you can set the color to one of four standard colors. The new color must be given as a string. Perform a case-insensitive check; if it is red, yellow, white, or black, set the r,g,b components of this color to their proper values. (You can find proper color values, for many common names, at the link above.)

If the user passes you any string which is not one of those four names, print out the following error message:


ERROR: Color.set_standard_color(): Invalid color name: xxxx

(Replace xxxx with the string you were passed.)

remove_red(self)

Set the red component of the current color to zero. Leave the green and blue components unchanged.
Usage Example

obj = Color(0,500,0)    # will get bounded to (0,255,0)
x = str(obj)            # returns "rgb(0,255,0)"
obj.set_standard_color("WHITE")

prob3.py - __eq__() and other methods

In the file prob3.py, you will write a single class Ball, which represents bouncy ball. Each ball has three different attributes: its color, material, and diameter. All fields must be private.

This class has the following methods:

__init__(self, color, material, diameter)

Constructor.

__str__(self)

Returns a string which represents the object. It must have the following format:


Ball(color=xxx, material=yyy, diameter=zzz)

(Replace xxx,yyy,zzz with the appropriate fields from your object.) Don't assume anything about the type of the various fields, just generate a string using Python's format() function, with the {} specifier.

You may assume that the diameter is a numeric type. You should not make assumptions about the types of the color and material.

__eq__(self, other)

Compares this object to another. You may assume that the other is not None, and that it is also of type Ball. (Later this semester, we'll make you do better checks, which don't make this assumption.)

Return True if the two objects are the same object (compare the references). Also return True if they are different objects, but all of their fields are equal. (Do simple checks with ==. Note that this means that, for any string fields, the comparison will be case sensitive.)

Return False if their fields are different.

get_color(self)
get_material(self)
get_diameter(self)

Getters for the three attributes. Note that while this class does not have traditional set_*() functions, the paint() method below can be used to change the color.

get_volume(self)

Returns the volume of the ball. (If you don't remember the formula for the volume of a sphere, look it up on Google.) To calculate this value, you'll need the value of Pi - make sure that you don't hardcode it yourself. Not only is it error-prone, it also wastes your time, and the time of everybody reading your code.

Instead, import the math library at the top of your file (just below the docstring), like this:

import math

and then you can use

math.pi

as a constant in your code.

paint(self, new_color)

Settor for the color.

bounce(self)

Bounces the ball on the ground. Usually, this method should simply print the line


Boing

However, if the material is "stone" (do a case-insensitive comparison), then you should instead print:


Thud

Usage Example

obj = Ball("Blue", "Plastic", 10)
obj.paint("Red")
obj2 = Ball("Red", "Plastic", 10)
if obj == obj2:    # should be True

Files you need to submit for Assg 5 short problems

  1. prob1.py
  2. prob2.py
  3. prob3.py

(本文出自csprojectedu.com,转载请注明出处)

你可能感兴趣的:(class)