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之总结参数的传递
Oct 10 Python
python删除列表中重复记录的方法
Apr 28 Python
在Django的URLconf中进行函数导入的方法
Jul 18 Python
python 字典(dict)按键和值排序
Jun 28 Python
Python生成器以及应用实例解析
Feb 08 Python
对python读写文件去重、RE、set的使用详解
Dec 11 Python
Django 1.10以上版本 url 配置注意事项详解
Aug 05 Python
手把手教你Python yLab的绘制折线图的画法
Oct 23 Python
Python函数递归调用实现原理实例解析
Aug 11 Python
python中字典增加和删除使用方法
Sep 30 Python
python实现跨年表白神器--你值得拥有
Jan 04 Python
Python中的min及返回最小值索引的操作
May 10 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
据说是雅虎的一份PHP面试题附答案
2009/01/07 PHP
PHP学习 变量使用总结
2011/03/24 PHP
一些需要禁用的PHP危险函数(disable_functions)
2012/02/23 PHP
二招解决php乱码问题
2012/03/25 PHP
微信公众平台天气预报功能开发
2014/07/06 PHP
PHP保存带BOM文件的方法
2015/02/12 PHP
php提交表单发送邮件的方法
2015/03/20 PHP
PHP设置头信息及取得返回头信息的方法
2016/01/25 PHP
浅谈Laravel队列实现原理解决问题记录
2017/08/19 PHP
PHP实现唤起微信支付功能
2019/02/18 PHP
JavaScript中出现乱码的处理心得
2009/12/24 Javascript
3Z版基于jquery的图片复选框(asp.net+jquery)
2010/04/12 Javascript
理解Javascript_09_Function与Object
2010/10/16 Javascript
不提示直接关闭网页窗口的JS示例代码
2013/12/17 Javascript
JavaScript实现检查页面上的广告是否被AdBlock屏蔽了的方法
2014/11/03 Javascript
JavaScript的String字符串对象常用操作总结
2016/05/26 Javascript
js实现无缝循环滚动
2020/06/23 Javascript
jQuery插件echarts设置折线图中折线线条颜色和折线点颜色的方法
2017/03/03 Javascript
Vue-Router的使用方法
2018/09/05 Javascript
iView框架问题整理小结
2018/10/16 Javascript
JS实现扫码枪扫描二维码功能
2020/01/03 Javascript
Vue文本模糊匹配功能如何实现
2020/07/30 Javascript
Python使用scrapy采集数据过程中放回下载过大页面的方法
2015/04/08 Python
python3.4用循环往mysql5.7中写数据并输出的实现方法
2017/06/20 Python
Python探索之URL Dispatcher实例详解
2017/10/28 Python
Python调用服务接口的实例
2019/01/03 Python
Python中文件的写入读取以及附加文字方法
2019/01/23 Python
Python动态参数/命名空间/函数嵌套/global和nonlocal
2019/05/29 Python
美国最大的存储市场:SpareFoot
2018/07/23 全球购物
高级3D打印市场:Gambody
2019/12/26 全球购物
主管竞聘书范文
2014/03/31 职场文书
《陈涉世家》教学反思
2014/04/12 职场文书
田径运动会通讯稿
2014/09/13 职场文书
2015医德医风个人工作总结
2015/04/02 职场文书
婚礼男方父母答谢词
2015/09/29 职场文书
基于Redis zSet实现滑动窗口对短信进行防刷限流的问题
2022/02/12 Redis