Python——类属性 类方法和静态方法

需求:1.设计一个Game类。
2.定义一个top_score,记录历史最高分。
3.定义实例属性player_name记录玩家姓名。
4.定义静态方法show_help显示游戏帮助信息。

要实现以下功能:
查看帮助信息,查看历史最高分,创建对象开始游戏。

class Game(object):

    #类属性:
    top_score = 0

    #实例属性:
    def __init__(self, player_name):
        self.player_name = player_name

    #静态方法,不访问类属性和实例属性:
    @staticmethod
    def show_help():
        print("这里是游戏帮助")

    #类方法,只访问类属性:
    @classmethod
    def show_top_score(cls):
        print("历史记录:%d" % cls.top_score)

    #实例方法,访问实例属性,也可访问类属性:
    def start_game(self):
        print("%s开始游戏" % self.player_name)

Game.show_help()
Game.show_top_score()

xiaoming = Game("小明")
xiaoming.start_game()

结果:
这里是游戏帮助
历史记录:0
小明开始游戏

你可能感兴趣的:(Python——类属性 类方法和静态方法)