Python中staticmethod和classmethod的作用与区别


Posted in Python onOctober 11, 2018

一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。

而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。

这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。

既然@staticmethod和@classmethod都可以直接类名.方法名()来调用,那他们有什么区别呢

从它们的使用上来看

  • @staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
  • @classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。

如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。

而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。

要明白,什么是实例方法、静态方法和类方法:

class Demo(object):
 def instance_method(self, your_para):
 """
 this is an instance_method
 you should call it like the follow:
 a = Demo()
 a.instance_method(your_para)
 plus: in python, we denote 'cls' as latent para of Class
 while 'self' as latent para of the instance of the Class
 :param your_para: 
 :return: 
 """
 print("call instance_method and get:", your_para)
 @classmethod
 def class_method(cls, your_para):
 """
 this is a class_method
 you can call it like the follow:
 method1:
 a = Demo()
 a.class_method(your_para)
 method2:
 Demo.class_method
 plus: in python, we denote 'cls' as latent para of Class
 while 'self' as latent para of the instance of the Class
 :param your_para: 
 :return: 
 """
 print("call class_method and get:", your_para)
 @staticmethod
 def static_method(your_para):
 """
 this is a static_method and you can call it like the 
 methods of class_method
 :param your_para: 
 :return: 
 """
 print("call static_method and get:", your_para)

虽然类方法在调用的时候没有显式声明cls,但实际上类本身是作为隐含参数传入的。这就像实例方法在调用的时候也没有显式声明self,但实际上实例本身是作为隐含参数传入的。

对于静态函数,我们一般把与类无关也与实例无关的函数定义为静态函数。例如入口检查的函数就最好定义成静态函数。

类方法的妙处, 在继承中的作用:

class Fruit(object):
 total = 0 # 这是一个类属性
 @classmethod
 def print_total(cls):
 print('this is the ', cls, '.total:', cls.total, ' and its id: ', id(cls.total)) # cls是类本身,打印类属性total的值
 print('this is the Fruit.total:', Fruit.total, 'and its id: ', id(Fruit.total))
 print("=======================")
 @classmethod
 def set(cls, value):
 cls.total = value
class Apple(Fruit):
 pass
class Orange(Fruit):
 pass
app1 = Apple()
app1.set(10)
app1.print_total()
Apple.print_total()
Fruit.set(2)
app1.print_total()
Fruit.print_total()
"""
output:
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 0 and its id: 1355200944
=======================
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 0 and its id: 1355200944
=======================
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 2 and its id: 1355201008
=======================
this is the <class '__main__.Fruit'> .total: 2 and its id: 1355201008
this is the Fruit.total: 2 and its id: 1355201008
=======================
"""

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
使用python实现递归版汉诺塔示例(汉诺塔递归算法)
Apr 08 Python
python实现简易内存监控
Jun 21 Python
Python3实现转换Image图片格式
Jun 21 Python
Django项目中实现使用qq第三方登录功能
Aug 13 Python
pytorch 预训练层的使用方法
Aug 20 Python
在python3中使用shuffle函数要注意的地方
Feb 28 Python
python3 sleep 延时秒 毫秒实例
May 04 Python
python 爬取B站原视频的实例代码
Sep 09 Python
Selenium关闭INFO:CONSOLE提示的解决
Dec 07 Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 Python
Python一行代码实现自动发邮件功能
May 30 Python
python运行脚本文件的三种方法实例
Jun 25 Python
对Python 窗体(tkinter)文本编辑器(Text)详解
Oct 11 #Python
详谈Python 窗体(tkinter)表格数据(Treeview)
Oct 11 #Python
Python GUI布局尺寸适配方法
Oct 11 #Python
10 行 Python 代码教你自动发送短信(不想回复工作邮件妙招)
Oct 11 #Python
对Python 窗体(tkinter)树状数据(Treeview)详解
Oct 11 #Python
Django 路由系统URLconf的使用
Oct 11 #Python
Python 中的lambda函数介绍
Oct 10 #Python
You might like
解析phpstorm + xdebug 远程断点调试
2013/06/20 PHP
Yii2实现多域名跨域同步登录退出
2017/02/04 PHP
Laravel find in set排序实例
2019/10/09 PHP
javascript编程起步(第四课)
2007/02/27 Javascript
javascript支持firefox,ie7页面布局拖拽效果代码
2007/12/20 Javascript
利用js对象弹出一个层
2008/03/26 Javascript
JQuery 风格的HTML文本转义
2009/07/01 Javascript
Javascript Math ceil()、floor()、round()三个函数的区别
2010/03/09 Javascript
jQuery.extend()、jQuery.fn.extend()扩展方法示例详解
2014/05/08 Javascript
深入理解JS正则表达式---分组
2016/07/18 Javascript
根据输入邮箱号跳转到相应登录地址的解决方法
2016/12/13 Javascript
vue指令以及dom操作详解
2017/03/04 Javascript
Vue.js实战之组件的进阶
2017/04/04 Javascript
Javascript中click与blur事件的顺序详析
2017/04/25 Javascript
Less 安装及基本用法
2018/05/05 Javascript
TypeScript基础入门教程之三重斜线指令详解
2018/10/22 Javascript
vue使用@scroll监听滚动事件时,@scroll无效问题的解决方法详解
2019/10/15 Javascript
JS实现点星星消除小游戏
2020/03/24 Javascript
[59:36]2018DOTA2亚洲邀请赛 4.3 突围赛 Secret vs VG 第二场
2018/04/04 DOTA
Python实现Tab自动补全和历史命令管理的方法
2015/03/12 Python
Python下线程之间的共享和释放示例
2015/05/04 Python
使用Python的urllib和urllib2模块制作爬虫的实例教程
2016/01/20 Python
Python交互环境下实现输入代码
2018/06/22 Python
Pandas统计重复的列里面的值方法
2019/01/30 Python
用Anaconda安装本地python包的方法及路径问题(图文)
2019/07/16 Python
Flask框架模板继承实现方法分析
2019/07/31 Python
对Django 转发和重定向的实例详解
2019/08/06 Python
简单瞅瞅Python vars()内置函数的实现
2019/09/27 Python
pycharm如何实现跨目录调用文件
2020/02/28 Python
用python批量下载apk
2020/12/29 Python
python数据抓取3种方法总结
2021/02/07 Python
优质飞蝇钓和渔具:RiverBum
2020/05/10 全球购物
传播学专业毕业生自荐信
2013/11/04 职场文书
劳务派遣管理制度(样本)
2019/08/23 职场文书
详解非极大值抑制算法之Python实现
2021/06/28 Python
golang生成并解析JSON
2022/04/14 Golang