类方法(静态方法、类方法、实例方法)

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()
game = Game("小明")
game.start_game()

静态方法和类方法用类名.方法名调用

Game.show_help()

猜你喜欢

转载自blog.csdn.net/qq_45156021/article/details/124538217
今日推荐