Python-黑马方法综合案例(个人练习)-类属性、实例属性、静态方法、类方法、实例方法基础

需求:

  1. 设计一个 Game 类

  2. 属性:

    1. 定义一个类属性 top_score 记录游戏的 历史最高分

    2. 定义一个实例属性 player_name 记录当前游戏的玩家姓名

  3. 方法:

    1. 静态方法 show_help 显示游戏帮助信息

    2. 类方法 show_top_score 显示历史最高分 

    3. 实例方法 start_game 开始当前玩家的游戏

  4. 主程序步骤:

    1. 查看帮助信息

    2. 查看历史最高分

    3. 创建游戏对象、开始游戏


运行效果:

Python-黑马方法综合案例(个人练习)-类属性、实例属性、静态方法、类方法、实例方法基础_第1张图片


代码:

# 定义一个 Game 类
class Game(object):

    # 定义一个类属性 top_score
    top_score = 0

    # 定义一个实例属性 player_name
    def __init__(self, player_name):
        self.player_name = player_name

    # 静态方法 show_help
    @staticmethod
    def show_help():
        print("游戏规则:FREE")

    # 类方法 show_top_score
    @classmethod
    def show_top_score(cls):
        print(f"目前游戏历史最高分为{cls.top_score}分")

    # 实例方法 start_game
    def start_game(self):
        print(f"创建游戏对象:{self.player_name},开始游戏")


# 1)查看帮助信息
Game.show_help()

# 2)查看历史最高分
Game.show_top_score()

# 3)创建游戏对象
Kox = Game("Kox")
Kox.start_game()

你可能感兴趣的:(Python基础,python)