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删除空文件和空文件夹的方法
Jul 14 Python
深入理解Django的自定义过滤器
Oct 17 Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
Jan 04 Python
python 中的list和array的不同之处及转换问题
Mar 13 Python
Python在groupby分组后提取指定位置记录方法
Apr 20 Python
python实现支付宝当面付(扫码支付)功能
May 30 Python
Python subprocess模块功能与常见用法实例详解
Jun 28 Python
python3中property使用方法详解
Apr 23 Python
解决Keras使用GPU资源耗尽的问题
Jun 22 Python
基于CentOS搭建Python Django环境过程解析
Aug 24 Python
用python批量移动文件
Jan 14 Python
完美处理python与anaconda环境变量的冲突问题
Apr 07 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
在DC的漫画和电影中,蝙蝠侠的宿敌,小丑的真名是什么?
2020/04/09 欧美动漫
安装APACHE
2007/01/15 PHP
php生成随机密码的三种方法小结
2010/09/04 PHP
老生常谈ThinkPHP中的行为扩展和插件(推荐)
2017/05/05 PHP
JQuery toggle使用分析
2009/11/16 Javascript
jQuery中add实现同时选择两个id对象
2010/10/22 Javascript
javascript 闭包
2011/09/15 Javascript
点击隐藏页面左栏或右栏实现js代码
2013/04/01 Javascript
原生javascript实现无间缝滚动示例
2014/01/28 Javascript
全面解析Bootstrap弹窗的实现方法
2015/12/01 Javascript
学习Angularjs分页指令
2016/07/01 Javascript
AngularJs用户登录问题处理(交互及验证、阻止FQ处理)
2017/10/26 Javascript
Three.js实现3D机房效果
2018/12/30 Javascript
[01:02:32]DOTA2-DPC中国联赛 正赛 iG vs PSG.LGD BO3 第二场 2月26日
2021/03/11 DOTA
在Mac OS上使用mod_wsgi连接Python与Apache服务器
2015/12/24 Python
python数据类型_字符串常用操作(详解)
2017/05/30 Python
Python开发微信公众平台的方法详解【基于weixin-knife】
2017/07/08 Python
Python语言描述机器学习之Logistic回归算法
2017/12/21 Python
python+opencv轮廓检测代码解析
2018/01/05 Python
Python装饰器用法实例总结
2018/05/26 Python
python实现对图片进行旋转,放缩,裁剪的功能
2019/08/07 Python
python3实现的zip格式压缩文件夹操作示例
2019/08/17 Python
django 实现celery动态设置周期任务执行时间
2019/11/19 Python
Python Selenium参数配置方法解析
2020/01/19 Python
浅谈pymysql查询语句中带有in时传递参数的问题
2020/06/05 Python
瑞士领先的网上超市:LeShop.ch
2018/11/14 全球购物
LUISAVIAROMA中国官网:时尚奢侈品牌购物网站
2020/11/01 全球购物
在c#中using和new这两个关键字有什么意义
2013/05/19 面试题
编辑个人求职信范文
2013/09/21 职场文书
餐厅考勤管理制度
2014/01/28 职场文书
三方股份合作协议书
2014/10/13 职场文书
销售员态度差检讨书
2014/10/26 职场文书
出国留学自荐信模板
2015/03/06 职场文书
驳回起诉裁定书
2015/05/19 职场文书
2016元旦文艺汇演主持词
2015/07/06 职场文书
html输入两个数实现加减乘除功能
2021/07/01 HTML / CSS