麦子学院——Python面向对象编程(P8类方法和静态方法)

题目

编写一个色子类:
1、具有6个面,每个面为一种颜色
2、每种颜色代表一个数值(1-6)
3、实现一个通过颜色计算两种其代表数值和的静态方法
4、实现一个类方法(gen_dice)用于产生这个类的实例

答案

class Dice:

    def __init__(self, up = "red", bottom = "green", left = "yellow",\
                 right = "blue", front = "orange", back = "pink"):
        self.up = up
        self.bottom = bottom
        self.left = left
        self.right = right
        self.front = front
        self.back = back

    value = {"red":1, "green":6, "yellow":2,\
             "blue":5, "orange":3, "pink":5} #red-1 bottom-6 left-2 right-5 front-3 back-5

    @staticmethod
    def calculate(color1, color2):
        if color1 in ["red", "green", "yellow", "blue", "orange", "pink"]:
            if color2 in ["red", "green", "yellow", "blue", "orange", "pink"]:
                result = Dice.value[color1] + Dice.value[color2]
                return result
            else:
                print("color2 not found!")
        else:
            print("color1 not found!")

    @classmethod
    def gen_dice(cls):
        return cls()

测试

if __name__ == "__main__":
    print(Dice.calculate("green","blue"))   #11
    a = Dice.gen_dice()
    print(a.calculate("red","pink"))    #6

你可能感兴趣的:(麦子学院——Python面向对象编程(P8类方法和静态方法))