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和C/C++交互的几种方法总结
May 11 Python
遗传算法之Python实现代码
Oct 10 Python
python实现redis三种cas事务操作
Dec 19 Python
儿童学习python的一些小技巧
May 27 Python
基于tensorflow加载部分层的方法
Jul 26 Python
Django中如何使用sass的方法步骤
Jul 09 Python
numpy 声明空数组详解
Dec 05 Python
pycharm实现在子类中添加一个父类没有的属性
Mar 12 Python
python中upper是做什么用的
Jul 20 Python
如何用PyPy让你的Python代码运行得更快
Dec 02 Python
Django 如何实现文件上传下载
Apr 08 Python
详解Python描述符的工作原理
Jun 11 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 strtotime函数用法、实现原理和源码分析
2015/02/04 PHP
Yii框架Session与Cookie使用方法示例
2019/10/14 PHP
PHP var关键字相关原理及使用实例解析
2020/07/11 PHP
xss文件页面内容读取(解决)
2010/11/28 Javascript
JavaScript中去掉数组中的重复值的实现方法
2011/08/03 Javascript
JS中setTimeout()的用法详解
2013/04/14 Javascript
对jQuery的事件绑定的一些思考(补充)
2013/04/20 Javascript
js关闭浏览器窗口及检查浏览器关闭事件
2013/09/03 Javascript
js模拟C#中List的简单实例
2014/03/06 Javascript
JS实现鼠标框选效果完整实例
2016/06/20 Javascript
基于AngularJS前端云组件最佳实践
2016/10/20 Javascript
Bootstrap CSS使用方法
2016/12/23 Javascript
JavaScript模拟文件拖选框样式v1.0的实例
2017/08/04 Javascript
VueRouter导航守卫用法详解
2017/12/25 Javascript
JavaScript中click和onclick本质区别与用法分析
2018/06/07 Javascript
JS实现提示效果弹出及延迟隐藏的功能
2019/08/26 Javascript
关于JS解构的5种有趣用法
2019/09/05 Javascript
快速解决element的autofocus失效问题
2020/09/08 Javascript
vue的$http的get请求要加上params操作
2020/11/12 Javascript
python线程中同步锁详解
2018/04/27 Python
浅谈Python2之汉字编码为unicode的问题(即类似\xc3\xa4)
2019/08/12 Python
python递归函数求n的阶乘,优缺点及递归次数设置方式
2020/04/02 Python
Python 程序报错崩溃后如何倒回到崩溃的位置(推荐)
2020/06/23 Python
shell程序中如何注释
2012/02/17 面试题
篝火晚会策划方案
2014/05/16 职场文书
售房协议书
2014/08/19 职场文书
党员个人剖析材料2014
2014/10/08 职场文书
工作失误检讨书
2015/01/26 职场文书
庆祝教师节活动总结
2015/03/23 职场文书
2015年乡镇平安建设工作总结
2015/05/13 职场文书
收入证明申请书
2015/06/12 职场文书
航班延误投诉信
2015/07/02 职场文书
早安问候语大全
2015/11/10 职场文书
看古人们是如何赞美老师的?
2019/07/08 职场文书
Nginx服务器如何设置url链接
2021/03/31 Servers
redis数据结构之压缩列表
2022/03/21 Redis