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中reader的next用法
Jul 24 Python
python对html过滤处理的方法
Oct 21 Python
详解Python logging调用Logger.info方法的处理过程
Feb 12 Python
Python爬取智联招聘数据分析师岗位相关信息的方法
Aug 13 Python
python列表返回重复数据的下标
Feb 10 Python
python 安装库几种方法之cmd,anaconda,pycharm详解
Apr 08 Python
Python ini文件常用操作方法解析
Apr 26 Python
django admin管理工具自定义时间区间筛选器DateRangeFilter介绍
May 19 Python
python不同系统中打开方法
Jun 23 Python
python对批量WAV音频进行等长分割的方法实现
Sep 25 Python
几款好用的python工具库(小结)
Oct 20 Python
浅谈哪个Python库才最适合做数据可视化
Jun 28 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
极典R601SW收音机
2021/03/02 无线电
PHP用身份证号获取星座和生肖的方法
2013/11/07 PHP
必须收藏的23个php实用代码片段
2016/02/02 PHP
Laravel学习笔记之Artisan命令生成自定义模板的方法
2018/11/22 PHP
用脚本调用样式的几种方法
2006/12/09 Javascript
地震发生中逃生十大法则
2008/05/12 Javascript
javascript 原型继承介绍
2011/08/30 Javascript
JQuery动画和停止动画实例代码
2013/03/01 Javascript
防止Node.js中错误导致进程阻塞的办法
2016/08/11 Javascript
vue.js中$watch的用法示例
2016/10/04 Javascript
js验证手机号、密码、短信验证码代码工具类
2020/06/24 Javascript
javascript基础知识之html5轮播图实例讲解(44)
2017/02/17 Javascript
深入理解angular2启动项目步骤
2017/07/15 Javascript
JS+HTML+CSS实现轮播效果
2017/11/28 Javascript
[54:41]2018DOTA2亚洲邀请赛3月30日 小组赛B组 VGJ.T VS paiN
2018/03/31 DOTA
在django中使用自定义标签实现分页功能
2017/07/04 Python
python WindowsError的错误代码详解
2017/07/23 Python
Python实现矩阵加法和乘法的方法分析
2017/12/19 Python
python3利用venv配置虚拟环境及过程中的小问题小结
2018/08/01 Python
Python代码打开本地.mp4格式文件的方法
2019/01/03 Python
教你一步步利用python实现贪吃蛇游戏
2019/06/27 Python
Python+selenium点击网页上指定坐标的实例
2019/07/05 Python
python通过robert、sobel、Laplace算子实现图像边缘提取详解
2019/08/21 Python
python nmap实现端口扫描器教程
2020/05/28 Python
Python+OpenCV实现旋转文本校正方式
2020/01/09 Python
tensorflow实现读取模型中保存的值 tf.train.NewCheckpointReader
2020/02/10 Python
德国最大的服装、鞋子和配件在线商店之一:Outfits24
2019/07/23 全球购物
应届大学生自荐信格式
2013/09/21 职场文书
工程建设实施方案
2014/03/14 职场文书
大学开学计划书
2014/04/30 职场文书
会计系毕业求职信
2014/08/07 职场文书
食品委托检验协议书范本
2014/09/12 职场文书
解约证明模板
2015/06/19 职场文书
《女娲补天》读后感5篇
2019/12/31 职场文书
sqlserver连接错误之SQL评估期已过的问题解决
2022/03/23 SQL Server
pycharm安装深度学习pytorch的d2l包失败问题解决
2022/03/25 Python