基础DAY9-类方法和静态方法

class Game(object):
    # 定义一个类属性,来记录游戏的历史最高分
    top_score = 10

    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()
# 创建游戏对象,开始游戏
player = Game("xiaoming")
player.start_game()
综合案列

  

class Tool(object):
    # 使用赋值语句定义类属性,记录所有工具对象的数量
    count = 0
    @classmethod
    def show_tool_count(cls):
        print("工具对象的数量%d" % cls.count)
    def __init__(self, name):
        self.name = name
        # 让类属性的值+1
        Tool.count += 1
# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("钳子")
tool3 = Tool("夹子")
tool4 = Tool("电钻")
# 调用类方法
Tool.show_tool_count()
类方法

class Dog(object):
    count = 0
    @staticmethod
    def run():
        # 不需要访问实例属性也不需要访问类属性的方法
        print("小狗要跑")
    def __init__(self):
        pass
# 通过类名.调用静态方法- 不需要创建对象
Dog.run()
静态方法
class Game(object):
    # 定义一个类属性,来记录游戏的历史最高分
    top_score = 10

    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()
# 创建游戏对象,开始游戏
player = Game("xiaoming")
player.start_game()
类方法,实例方法,静态方法
原文地址:https://www.cnblogs.com/joycezhou/p/11391633.html