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实现将元祖转换成数组的方法
May 04 Python
Python实现二叉树结构与进行二叉树遍历的方法详解
May 24 Python
Python 40行代码实现人脸识别功能
Apr 02 Python
python实现判断一个字符串是否是合法IP地址的示例
Jun 04 Python
python中的tcp示例详解
Dec 09 Python
python初学者,用python实现基本的学生管理系统(python3)代码实例
Apr 10 Python
Django框架模板语言实例小结【变量,标签,过滤器,继承,html转义】
May 23 Python
利用Python实现手机短信监控通知的方法
Jul 22 Python
python-numpy-指数分布实例详解
Dec 07 Python
python except异常处理之后不退出,解决异常继续执行的实现
Apr 25 Python
python代码如何注释
Jun 01 Python
4款Python 类型检查工具,你选择哪个呢?
Oct 30 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
在任意字符集下正常显示网页的方法一
2007/04/01 PHP
php 在线打包_支持子目录
2008/06/28 PHP
php中获取远程客户端的真实ip地址的方法
2011/08/03 PHP
浅谈PHP中Stream(流)
2015/06/08 PHP
PHP设计模式之装饰器模式定义与用法简单示例
2018/08/13 PHP
php命名空间设计思想、用法与缺点分析
2019/07/17 PHP
基于jquery的checkbox下拉框插件代码
2010/06/25 Javascript
js截取小数点后几位的写法
2013/11/14 Javascript
js replace替换所有匹配的字符串
2014/02/13 Javascript
Javascript排序算法之合并排序(归并排序)的2个例子
2014/04/04 Javascript
深入理解JavaScript系列(40):设计模式之组合模式详解
2015/03/04 Javascript
JavaScript中的boolean布尔值使用学习及相关技巧讲解
2016/05/26 Javascript
js实现常用排序算法
2016/08/09 Javascript
用jQuery的AJax实现异步访问、异步加载
2016/11/02 Javascript
微信小程序 二维码canvas绘制实例详解
2017/01/06 Javascript
Javascript 使用ajax与C#获取文件大小实例详解
2017/01/13 Javascript
jQuery实现的简单悬浮层功能完整实例
2017/01/23 Javascript
AngularJS自定义指令实现面包屑功能完整实例
2017/05/17 Javascript
微信小程序slider组件使用详解
2018/01/31 Javascript
vuex页面刷新后数据丢失的方法
2019/01/17 Javascript
原生JS实现动态添加新元素、删除元素方法
2019/05/05 Javascript
js实现筛选功能
2020/11/24 Javascript
jQuery实现可以扩展的日历
2020/12/01 jQuery
Python使用os模块和fileinput模块来操作文件目录
2016/01/19 Python
对python读取CT医学图像的实例详解
2019/01/24 Python
python 五子棋如何获得鼠标点击坐标
2019/11/04 Python
Python获取统计自己的qq群成员信息的方法
2019/11/15 Python
python:动态路由的Flask程序代码
2019/11/22 Python
Mac中PyCharm配置Anaconda环境的方法
2020/03/04 Python
有趣的Python图片制作之如何用QQ好友头像拼接出里昂
2020/04/22 Python
python自定义函数def的应用详解
2020/06/03 Python
HTML5离线应用与客户端存储的实现
2018/05/03 HTML / CSS
JD Sports丹麦:英国领先的运动时尚零售商
2020/11/24 全球购物
校园歌咏比赛主持词
2014/03/18 职场文书
公司委托书格式范本
2014/09/16 职场文书
学校四风问题对照检查材料思想汇报
2014/09/26 职场文书