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 pickle类库介绍(对象序列化和反序列化)
Nov 21 Python
基于Python 的进程管理工具supervisor使用指南
Sep 18 Python
对TensorFlow的assign赋值用法详解
Jul 30 Python
Pandas Shift函数的基础入门学习笔记
Nov 16 Python
Python程序包的构建和发布过程示例详解
Jun 09 Python
python 杀死自身进程的实现方法
Jul 01 Python
python plotly画柱状图代码实例
Dec 13 Python
Python自动巡检H3C交换机实现过程解析
Aug 14 Python
Python-split()函数实例用法讲解
Dec 18 Python
Pytorch实现WGAN用于动漫头像生成
Mar 04 Python
python实现自动清理文件夹旧文件
May 10 Python
python中pycryto实现数据加密
Apr 29 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
Smarty结合Ajax实现无刷新留言本实例
2007/01/02 PHP
php获取图片信息的方法详解
2015/12/10 PHP
关于锚点跳转及jQuery下相关操作与插件
2012/10/01 Javascript
推荐6款基于jQuery实现图片效果插件
2014/12/07 Javascript
浅谈javascript构造函数与实例化对象
2015/06/22 Javascript
JS获取时间的相关函数及时间戳与时间日期之间的转换
2016/02/04 Javascript
json与jsonp知识小结(推荐)
2016/08/16 Javascript
jquery控制页面的展开和隐藏实现方法(推荐)
2016/10/15 Javascript
echarts3 使用总结(绘制各种图表,地图)
2017/01/05 Javascript
利用HBuilder打包前端开发webapp为apk的方法
2017/11/13 Javascript
Node使用Sequlize连接Mysql报错:Access denied for user ‘xxx’@‘localhost’
2018/01/03 Javascript
jQuery实现的简单图片轮播效果完整示例
2018/02/08 jQuery
对vue生命周期的深入理解
2020/12/03 Vue.js
[02:33]DOTA2英雄基础教程 司夜刺客
2013/12/04 DOTA
[38:21]2014 DOTA2国际邀请赛中国区预选赛5.21 TongFu VS LGD-CDEC
2014/05/22 DOTA
Python实现在线程里运行scrapy的方法
2015/04/07 Python
浅谈python字符串方法的简单使用
2016/07/18 Python
用python实现简单EXCEL数据统计的实例
2017/01/24 Python
python 获取键盘输入,同时有超时的功能示例
2018/11/13 Python
Python在图片中插入大量文字并且自动换行
2019/01/02 Python
python实现Virginia无密钥解密
2019/03/20 Python
Python flask框架post接口调用示例
2019/07/03 Python
Numpy与Pytorch 矩阵操作方式
2019/12/27 Python
python实现坦克大战
2020/04/24 Python
python实现学生成绩测评系统
2020/06/22 Python
django和flask哪个值得研究学习
2020/07/31 Python
html5实现的便签特效(实战分享)
2013/11/29 HTML / CSS
荷兰鞋子在线:Nelson Schoenen
2017/12/25 全球购物
香蕉共和国工厂店:Banana Republic Factory
2018/06/09 全球购物
伦敦香水公司:The London Perfume Company
2019/11/13 全球购物
沙特阿拉伯家用电器和电子产品购物网站:Sheta and Saif
2020/04/03 全球购物
The North Face意大利官网:服装、背包和鞋子
2020/06/17 全球购物
EJB与JAVA BEAN的区别
2016/08/29 面试题
网络工程专业毕业生推荐信
2013/10/28 职场文书
团队精神口号
2014/06/06 职场文书
中学生秋季运动会广播稿
2014/09/21 职场文书