1.(a)下图中所示的类可用于描述各种形状的属性以及对这些形状的操作:
为这些类创建代码,并通过编写一个简单的函数test_shopes()-来演示它们的行为,以创建各种对象并调用它们的方法。
import math
class Shape:
def __init__(self, colour):
self._colour = colour
def get_colour(self):
return self._colour
class Circle(Shape):
def __init__(self, colour, radius=1.0):
self._radius = radius
super().__init__(colour)
def get_area(self):
""" Calculate the area of a Circle."""
return math.pi * self._radius * self._radius
def get_radius(self):
""" Return the radius of a Circle."""
return self._radius
def __str__(self):
return 'Circle of radius ' + str(self._radius) + \
' & colour ' + self._colour
class Rectangle(Shape):
def __init__(self, colour, width=2.0, length=3.0):
self._width = width
self._length = length
super().__init__(colour)
def get_area(self):
""" Calculate the area of a Rectangle."""
return self._width * self._length
def get_perimeter(self):
""" Calculate the perimeter of a Rectangle."""
return (self._length * 2) + (self._width * 2)
def __str__(self):
return 'Rectangle of width ' + str(self._width) + \
', length ' + str(self._length) + ' & colour ' + self._colour
class Cylinder(Circle):
def __init__(self, colour, radius=2.5, height=5.0):
self._height = height
super().__init__(colour, radius)
def get_area(self):
""" Calculate the area of a Cylinder.
Note call to Circle class get_area() method. """
return (2 * math.pi * self._radius * self._height) + \
(2 * super().get_area())
def get_volume(self):
""" Calculate the volumer of a Cylinder.
Note call to Circle class get_area() method. """
return super().get_area() * self._height
def __str__(self):
return 'Cylinder of radius ' + str(self._radius) + \
', height ' + str(self._height) + ' & colour ' + self._colour
def test_shapes():
cyl1 = Cylinder('green', 23.4)
print(cyl1)
print(cyl1.get_area())
print(cyl1.get_volume())
rect1 = Rectangle('magenta', 3.4)
print(rect1)
print(rect1.get_area())
print(rect1.get_perimeter())
circ1 = Circle('blue', 99.2)
print(circ1)
print(circ1.get_radius())
print(circ1.get_area())
if __name__ == "__main__": test_shapes()
1.(b)修改您的解决方案以引入一个新的类点(如下所示),它用于表示所创建的每个形状的新数据属性(中心)。(对于圆柱体,使用圆的中心形成其底座。)
import math
class Point:
""" Create a new Point, at coordinates x, y """
def __init__(self, x=0.0, y=0.0):
""" Create a new point at x, y """
self._x = x
self._y = y
def get_xcoord(self):
return self._x
def get_ycoord(self):
return self._y
def distance_from_origin(self):
""" Compute point distance from the origin """
return ((self._x ** 2) + (self._y ** 2)) ** 0.5
def __str__(self):
return "({0}, {1})".format(self._x, self._y)
class Shape:
""" Shape class now uses Point class to represent its centre."""
def __init__(self, x, y, colour):
self._colour = colour
self._centre = Point(x,y)
def get_colour(self):
return self._colour
class Circle(Shape):
def __init__(self, x, y, colour, radius=1.0):
self._radius = radius
super().__init__(x, y, colour)
def get_area(self):
""" Calculate the area of a Circle."""
return math.pi * self._radius * self._radius
def get_radius(self):
""" Return the radius of a Circle."""
return self._radius
def __str__(self):
return 'Circle of radius ' + str(self._radius) + \
' & colour ' + self._colour + ' @ ' + \
str(self._centre)
class Rectangle(Shape):
def __init__(self, x, y, colour, width=2.0, length=3.0):
self._width = width
self._length = length
super().__init__(x, y, colour)
def get_area(self):
""" Calculate the area of a Rectangle."""
return self._width * self._length
def get_perimeter(self):
""" Calculate the perimeter of a Rectangle."""
return (self._length * 2) + (self._width * 2)
def __str__(self):
return 'Rectangle of width ' + str(self._width) + \
', length ' + str(self._length) + ' & colour ' + \
self._colour + ' @ ' + str(self._centre)
class Cylinder(Circle):
def __init__(self, x, y, colour, radius=2.5, height=5.0):
self._height = height
super().__init__(x, y, colour, radius)
def get_area(self):
""" Calculate the area of a Cylinder.
Note call to Circle class get_area() method. """
return (2 * math.pi * self._radius * self._height) + \
(2 * super().get_area())
def get_volume(self):
""" Calculate the volumer of a Cylinder.
Note call to Circle class get_area() method. """
return super().get_area() * self._height
def __str__(self):
return 'Cylinder of radius ' + str(self._radius) + \
', height ' + str(self._height) + ' & colour ' + \
self._colour + ' @ ' + str(self._centre)
def test_shapes():
cyl1 = Cylinder(0.0, 0.0, 'green', 23.4)
print(cyl1)
print(cyl1.get_area())
print(cyl1.get_volume())
print(cyl1._centre.distance_from_origin())
rect1 = Rectangle(2.5, 4.0, 'magenta', 3.4)
print(rect1)
print(rect1.get_area())
print(rect1.get_perimeter())
print(rect1._centre.distance_from_origin())
circ1 = Circle(1.0, 1.0, 'blue', 99.2)
print(circ1)
print(circ1.get_radius())
print(circ1.get_area())
print(circ1._centre.distance_from_origin())
if __name__ == "__main__": test_shapes()
1.(c)在1(a)中,我们使用与圆的关系来建模一个圆柱形状。想想这个问题:我们真的能说一个圆柱体是一个圆圈吗?一个更好的解决方案是将一个圆柱体描述为由一个基圆和一个高度组成。重新制作您的解决方案,以便圆柱类表现为圆柱应该的行为,但不使用继承将其链接到圆。
class Cylinder(Shape):
def __init__(self, x, y, colour, radius=2.5, height=5.0):
self._height = height
""" Create an instance of Circle as value of _base attribute """
self._base = Circle(x, y, colour, radius)
def get_area(self):
""" Calculate the area of a Cylinder.
Note call to _base get_area() method. """
return (2 * math.pi * self._base._radius * self._height) + \
(2 * self._base.get_area())
def get_volume(self):
""" Calculate the volumer of a Cylinder.
Note call to _base get_area() method. """
return self._base.get_area() * self._height
def __str__(self):
return 'Cylinder of radius ' + str(self._base._radius) + \
', height ' + str(self._height) + ' & colour ' + \
self._base._colour + ' @ ' + str(self._base._centre)
2.Create a class Counter which can be used to create Python counter objects. 您的类应该有方法使计数器增加和减少指定的数量(如果没有给出值,则增加1)。您还应该保留已创建的计数器对象的数量的运行计数,以及所有计数器实例调用其增量方法的次数。
class Counter:
""" Simple Counter class using class and data attributes."""
increment_total = 0 # class attributes
counters_total = 0
def __init__(self):
self._my_total = 0 # data attribute
Counter.counters_total += 1
def reset(self):
self._my_total = 0
def increment(self, amount=1):
Counter.increment_total += 1
self._my_total += amount
def decrement(self, amount=1 ):
self._my_total -= amount
3.Define a custom Python Exception class which takes a string message as an attribute
class MyError(Exception):
""" My own exception class. """
def __init__(self, msg):
self.msg = msg
4.为一系列必要的类创建Python代码,以实现一个简单的街机游戏,您的选择。您应该包括属性、方法和类之间的适当关系。
例如,经典游戏《吃豆人1》就会有类来代表吃豆人、鬼魂(眨眼、小指、墨水和克莱德)、点、强力球、水果和迷宫——以及它们的属性和行为。
在这个阶段,没有必要实现游戏的图形,而应该关注关键对象和它们的行为。
class Character:
def __init__(self, x, y, sp):
self._x = x
self._y = y
self._speed = sp
def move(self, x_delta, y_delta):
self._x = self._x + x_delta
self._y = self._y + y_delta
class PacMan(Character):
_number_of_lives = 3
@classmethod
def check_lives(cls):
return cls._number_of_lives != 0
def __init__(self):
PacMan._number_of_lives -= 1
self._score = 0
super().__init__(0, -50, 15)
def eat(self, food):
if isinstance(food, Ghost):
if food._status == 'blue':
self._score += 500
food.die()
else:
self.die(food)
else:
self._score += food._points
food.remove()
def die(self, ghost):
# Code here to remove graphical representation of
# Pac-Man, play sound, etc.
print('PacMan >>> Oh no - I have been eaten by ' + ghost._name.title())
self._score = 0
class Ghost(Character):
def __init__(self, name):
self._name = name
self._status = 'normal'
super().__init__(0, 0, 10)
def edible(self):
self._status = 'blue'
self._speed = 5
def revive(self):
self._status = 'normal'
self._speed = 10
def die(self):
print(self._name.title() + ' >>> Oh no - I have been eaten by PacMan !!!')
# Code here to remove graphical representation of
# Ghost, play sound, animate eyes returning to centre, etc.
class Item:
def __init__(self, xi, yi):
self._xi = xi
self._yi = yi
# draw Item at position xi, yi
def remove(self):
pass
# Code here to remove graphical representation
# of item (dot, powerpill, etc)
class Dot(Item):
def __init__(self, x, y):
super().__init__(x, y)
self._points = 1
class PowerPill(Item):
def __init__(self, x, y):
super().__init__(x, y)
self._points = 10
def run():
# initial set-up
pac = PacMan()
blinky = Ghost('blinky')
pinky = Ghost('pinky')
inky = Ghost('inky')
clyde = Ghost('clyde')
# Code here to provide top-level loop to control
# execution of game...
if __name__ == "__main__": run()