美文网首页
Python类各种方法和属性定义

Python类各种方法和属性定义

作者: 不思九八 | 来源:发表于2020-01-05 22:46 被阅读0次

定义一个类Game

  • 游戏名称 “贪吃蛇”
  • 实例属性有“玩家”,“历史最高分”
  • 定义一个方法开始游戏start
  • 定义一个方法显示游戏名称show_game
  • 定义一个方法,显示游戏帮助信息show_help
class Game(object):
    name = "贪吃蛇"

    def __init__(self, player):
        self.player = player
        self.top_score = 267

    @property
    def current_player(self):
        return self.player
 
    @staticmethod
    def show_help():
        print("帮助信息:按Erter键开始游戏。")
 
    @classmethod
    def show_game(cls):
        print(cls.name.center(20, '*'))
 
    def start(self):
        print('{}开始游戏了,他的最高分为{}分。'.format(self.current_player, self.top_score))

Game.show_game()
Game.show_help()
game = Game("Jack")
game.start()

说明:

  • name:游戏名称,不因实例化而改变,定义为类属性

  • player、top_score: 每个玩家各不一样,定义为实例属性

  • current_player:获取当前玩家名字,使用@property修饰,变成属性,可想访问一般属性一样访问

    使用方式:

    self.current_player  # 在实例方法内部
    game.current_player  # 在类外部
    
  • show_game():使用@staticmethod修饰,因其访问了类属性name,故定义为类方法,调用方式如下:

    Game.show_game()  # 通过类名调用
    game.show_game() # 通过实例调用
    
  • show_help(): 因为没有使用任何类属性和调用任何类方法,故使用@staticmethod修饰,定义为静态方法,调用方式如下:

    Game.show_help()  # 通过类名调用
    game.show_help() # 通过实例调用
    
  • start():定义为实例方法,因为此方法访问了实例属性current_playertop_score

相关文章

网友评论

      本文标题:Python类各种方法和属性定义

      本文链接:https://www.haomeiwen.com/subject/tjthactx.html