python基础 #009 类方法和静态方法
1. 类方法
-
类方法需要用装饰器
@classmethod告诉解释器这是一个类方法 -
类方法的第一参数必须是
cls即当前由哪一个类调用这个方法,那么
cls就是当前这个类
class Person:
a = 100
def test():
print('111')
@classmethod
def clsmtd(cls):
# 调用类属性和方法
print(cls.a)
cls.test()
Person.clsmtd()
>>>: 100 111
2. 静态方法
-
静态方法内部,不需要访问类属性或实例属性,也不需要调用类方法或实例方法
-
静态方法需要用装饰器
@staticmethod告诉解释器这是一个静态方法 -
静态方法适用于类的说明
# 通过类名,调用静态方法,不需要创建对象 class Dog(object): @staticmethod def run(): print("pao~~~~~") Dog.run() >>>: pao~~~~~
3. 案例
案例一:游戏

class Game(object):
top_grade = 0
def __init__(self, player_name):
self.player_name = player_name
def start_game(self):
print("%s 开始游戏"%self.player_name)
@classmethod
def show_top_grade(cls):
print("最高分:%s"%cls.top_grade)
@staticmethod
def show_help():
print("游戏规则:-----------")
# 1.查看帮助信息
Game.show_help()
# 2.查看历史最高
Game.show_top_grade()
# 3.开始游戏
xiaoming = Game("小明")
xiaoming.start_game()
>>>:
游戏规则:-----------
最高分:0
小明 开始游戏
本文来自博客园,作者:{枫_Null},转载请注明原文链接:https://www.cnblogs.com/fengNull/articles/16622646.html

浙公网安备 33010602011771号