测牛学堂:软件测试python面向对象属性方法综合使用小案例

84 阅读1分钟

面向对象综合小案例

让我们通过一个小的案例练习,去更加深刻的掌握面向对象中类和对象的相关知识吧!
需求:
1 设计一个game类。
2 属性:
1 the_first记录游戏的最高分
2 player 记录当前游戏玩家的姓名
3 方法:
静态方法:help_msg:显示游戏帮助
类方法:show_the_first 显示历史最高分
实例方法:pyay_game 开始当前游戏:用随机数模拟游戏成绩即可
分析:
1 the_first记录游戏的最高分初始化是设置为0即可
2 实例的属性通过init函数去定义

代码实现

import random
class Game:
    the_first = 0
    def __init__(self,name):
        self.player = name
    @staticmethod
    def help_msg():
        print('游戏规则模拟:xx')
    @classmethod
    def show_the_first(cls):
        print(f'当前游戏最高分是:{cls.the_first}')

    def play_game(self):
        score = random.randint(1,100)
        print(f'{self.player},你的游戏得分:{score}')
        if score>Game.the_first:
            Game.the_first = score

if __name__ == '__main__':
    game1 = Game('小明')
    game1.help_msg()
    game1.show_the_first()
    game1.play_game()
    game1.show_the_first()
    game1.play_game()
    game1.show_the_first()