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 13 Python
如何利用Fabric自动化你的任务
Oct 20 Python
详解python中xlrd包的安装与处理Excel表格
Dec 16 Python
最近Python有点火? 给你7个学习它的理由!
Jun 26 Python
vscode 远程调试python的方法
Dec 01 Python
用Python将mysql数据导出成json的方法
Aug 21 Python
PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法
Aug 06 Python
opencv调整图像亮度对比度的示例代码
Sep 27 Python
python实现将列表中各个值快速赋值给多个变量
Apr 02 Python
Jupyter Notebook输出矢量图实例
Apr 14 Python
一篇文章搞懂python混乱的切换操作与优雅的推导式
Aug 23 Python
使用pd.merge表连接出现多余行的问题解决
Jun 16 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
用phpmyadmin更改mysql5.0登录密码
2008/03/25 PHP
php shell超强免杀、减少体积工具实现代码
2012/10/16 PHP
PHP中的str_repeat函数在JavaScript中的实现
2013/09/16 PHP
php生成随机字符串可指定纯数字、纯字母或者混合的
2014/04/18 PHP
PHP中创建和验证哈希的简单方法实探
2015/07/06 PHP
关于Aptana Studio生成自动备份文件的解决办法
2009/12/23 Javascript
[原创]js获取数组任意个不重复的随机数组元素
2010/03/15 Javascript
jquery 模拟雅虎首页的点击对话框效果
2010/04/11 Javascript
js格式化金额可选是否带千分位以及保留精度
2014/01/28 Javascript
JS实现网站菜单拖拽移位效果的方法
2015/09/24 Javascript
JavaScript实现简洁的俄罗斯方块完整实例
2016/03/01 Javascript
下雪了 javascript实现雪花飞舞
2020/08/02 Javascript
json对象与数组以及转换成js对象的简单实现方法
2016/06/24 Javascript
AngularJS入门教程之模块化操作用法示例
2016/11/02 Javascript
JS简单实现表格排序功能示例
2016/12/20 Javascript
简单实现jQuery级联菜单
2017/01/09 Javascript
React Native react-navigation 导航使用详解
2017/12/01 Javascript
Layui表格监听行单双击事件讲解
2019/11/14 Javascript
Python实现基于权重的随机数2种方法
2015/04/28 Python
Python django实现简单的邮件系统发送邮件功能
2017/07/14 Python
python批量读取txt文件为DataFrame的方法
2018/04/03 Python
python中的colorlog库使用详解
2019/07/05 Python
Python中typing模块与类型注解的使用方法
2019/08/05 Python
django组合搜索实现过程详解(附代码)
2019/08/06 Python
opencv python图像梯度实例详解
2020/02/04 Python
幼儿园长自我鉴定
2013/10/17 职场文书
玩具公司的创业计划书
2013/12/31 职场文书
保护环境建议书
2014/03/12 职场文书
售房委托书
2014/08/30 职场文书
党员干部群众路线个人整改措施
2014/09/18 职场文书
房屋转让协议书
2014/10/18 职场文书
基层党支部承诺书
2015/04/30 职场文书
2015毕业设计工作总结
2015/07/24 职场文书
通过Qt连接OpenGauss数据库的详细教程
2021/06/23 PostgreSQL
Redis 操作多个数据库的配置的方法实现
2022/03/23 Redis
GO语言异常处理分析 err接口及defer延迟
2022/04/14 Golang