9.2.3 静态方法
静态方法是一种普通函数,只不过位于类定义的命名空间中,它不会对任何实例对象进行操作。因为它位于类的命名空间中,所以可以通过“类名.类属性”或者“类名.类方法名()”来访问类属性、调用类方法。
在设计程序时,如果需要在某个类中封装某个方法,这个方法既不需要访问实例属性或者调用实例方法,也不需要访问类属性或者调用类方法,此时,可以将该方法封装成一个静态方法,即静态方法一般用于和类对象以及实例对象都无关的代码。
静态方法必须用装饰器“@staticmethod”来修饰。静态方法定义格式如下:
@staticmethod
def 静态方法名([形参列表])∶
函数体
静态方法的调用格式如下:
类名.静态方法名([实参列表])
实例对象名.静态方法名([实参列表])
【例9-5】设计一个Game类,类属性topScore用来记录游戏的最高分,实例属性name记录游戏名称,player记录玩家名称。方法menu()用来显示游戏菜单,该方法和类对象以及实例对象都没有关系,可以设计为静态方法。类方法showTopScore()用来显示当前游戏的最高分;实例方法startGame()、pauseGame()和exitGame()分别用来开始游戏、暂停游戏和结束游戏。__init__()方法用来初始化实例属性。(https://www.daowen.com)
代码如下:
import random
class Game:
topScore = 0 #类属性
@staticmethod #静态方法
def menu():
print( " ==========")
print( "1:游戏开始")
print( "2:游戏暂停")
print( "3:游戏结束")
print( " ========== ")
def __init__( self , name, player) :
self. name = name
self.player = player
self.score = 0
def startGame(self):
print(self.player + "开始打" + self.name + "游戏! ")
self.score = random.randint(0, 100) # 随机给出游戏分数print( self.player+"当前得分是:",self.score)
if self.score > Game.topScore:
Game.topScore = self.score
# 记录游戏的最高分
def pauseGame(self):
print(self.player + "的" + self.name + "游戏暂停!")
def exitGame(self):
print(self.name + " is over! ")
@ classmethod # 类方法,输出当前游戏的最高分
def showTopScore(cls):
print("游戏当前最高分是: ", cls.topScore)
#测试代码
game1 = Game("扫雷","小苏")
#创建了第一个游戏对象
game2 = Game("扫雷","小师")
#创建了第二个游戏对象
while True:
Game.menu()
choice = int(input("请输入选择:"))
if choice == 1:
game1.startGame()
game2.startGame()
elif choice == 2:
game1.pauseGame()
game2.pauseGame()
elif choice == 3:
game1.exitGame()
game2.exitGame()
break
Game.showTopScore()
运行结果:
==========
1:游戏开始
2:游戏暂停
3:游戏结束
==========
请输入选择:1
小苏开始打扫雷游戏!
小师开始打扫雷游戏!
==========
1:游戏开始
2:游戏暂停
3:游戏结束
==========
请输入选择:3
扫雷 is over!
扫雷 is over!
游戏当前最高分是: 65
程序分析:这是一个综合实例,涉及前面学习的类属性和实例属性以及实例方法、类方法和静态方法。本例中menu()方法就是静态方法,它和普通函数的作用类似,menu()方法的作用就是输出一个菜单。