Python @classmethod和@staticmethod装饰器使用介绍

@classmethod@staticmethod装饰器使用介绍

by:授客 QQ1033553122

 

简介

静态方法:类中用 @staticmethod装饰的不带 self 参数的方法。类的静态方法可以直接使用类名调用。

 

类方法: 默认有个cls参数,可以被类和对象调用,需要加上 @classmethod装饰器

 

普通方法: 默认有个self参数,且只能被对象调用。

 

代码

classDotaGame:

top_score = 0

 

def__init__(self, name):

self.name = name

 

@staticmethod

defprint_game_rules():

print("游戏规则:1 xxxx游戏规则1 \n 2 xxxx游戏规则2")

 

@classmethod

defprint_store(cls):

print("历史最高分: %s" % cls.top_score)

 

defprint_game_name(self):

print('开始 %s 游戏' % self.name)

 

DotaGame('dota').print_game_name()

 

DotaGame.print_store()

 

DotaGame.print_game_rules()

运行结果:

开始dota游戏

历史最高分: 0

游戏规则:1 xxxx游戏规则1

 2 xxxx游戏规则2

 

结论

1、对于不需要访问类实例属性,类实例方法,和类属性的函数定义成静态函数

 

2、对于需要访问类属性的定义成类函数

 

3、对于需要访问实例属性、实例方法的定义成实例函数

posted @ 2019-10-19 18:04  授客  阅读(1469)  评论(0编辑  收藏  举报