OOP作业

1.Now it is time to start creating you own object-oriented code in Python.
Define a class InputOutString which has at least two methods:
get_string : to get a string from console input
print_string : to print the string in upper case.
Also provide some simple code to test your class and its methods.
[HINT: You will need to use input() to get input from the console.]
class InputOutString:
    def __init__(self):
        self.s = ""

    def getString(self):
        self.s = input()

    def printString(self):
        print(self.s.upper())
2. (a) The classes shown in the diagram below can be used to describe the properties ofshapes of various
kinds and operations on those shapes:

# PROBLEM 2(a)
# This solution uses conventional and some default arguments to __init__()
# methods; could also have used keyword arguments (**kwargs) - but this solution
# is kept as simple as possible.

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()

# PROBLEM 3(b)
# Main change here is creation of Point class and its introduction into the Shape
# class; other changes are very minor - mostly changes to various __init__() methods.

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()

3.创建一个可用于创建Python计数器对象的类计数器。您的类应该有方法使计数器增加和减少指定的数量(如果没有给出值,则增加1)。您还应该保留已创建的计数器对象的数量的运行计数,以及所有计数器实例调用其增量方法的次数。

# Requires use of class attributes.

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

4.定义一个自定义的Python的Exception类,它将一个字符串消息作为一个属性

[提示:请记住,继承并不局限于用户定义的类,我们还可以专门化内置的Python类。

# To define a custom exception, we need to define a class inherited from the
# built-in class Exception.
# Remember that specialising existing Python classes is a powerful way to build
# programs quickly.

class MyError(Exception):
    """ My own exception class. """

    def __init__(self, msg):
        self.msg = msg

6.为一系列必要的类创建Python代码,以实现一个简单的街机游戏,您的选择。您应该包括属性、方法和类之间的适当关系。例如,经典游戏《吃豆人1》就有代表吃豆人、鬼魂(眨眼、小指、墨水和克莱德)、点、强力球、水果和迷宫以及它们的属性和行为。

在这个阶段,没有必要实现游戏的图形,而是你应该关注关键对象和它们的行为。对于那些对将来如何实现完整游戏感兴趣的人,请查看这里的Python小游戏库: https://www.pygame.org/wiki/about

# PROBLEM 6 (OPTIONAL)      
# Different students may attempt different games, and the associated
# objects and behaviours. What follows is a basic (incomplete) set of
# classes for Pac-Man - as a starting point.

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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值