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
Python编程之Re模块下的函数介绍
Oct 28 Python
Python读取视频的两种方法(imageio和cv2)
Apr 15 Python
Python实现修改IE注册表功能示例
May 10 Python
python简易实现任意位数的水仙花实例
Nov 13 Python
浅谈对pytroch中torch.autograd.backward的思考
Dec 27 Python
python解释器pycharm安装及环境变量配置教程图文详解
Feb 26 Python
浅谈python的elementtree模块处理中文注意事项
Mar 06 Python
python实现猜数游戏(保存游戏记录)
Jun 22 Python
如何使用Cython对python代码进行加密
Jul 08 Python
解决使用Pandas 读取超过65536行的Excel文件问题
Nov 10 Python
Python Pandas读取Excel日期数据的异常处理方法
Feb 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
WordPress中缩略图的使用以及相关技巧
2015/11/24 PHP
PHP实现QQ快速登录的方法
2016/09/28 PHP
js和jquery如何获取图片真实的宽度和高度
2014/09/28 Javascript
JavaScript实现按照指定长度为数字前面补零输出的方法
2015/03/19 Javascript
实例讲解js验证表单项是否为空的方法
2016/01/09 Javascript
Javascript的表单验证-揭开正则表达式的面纱
2016/03/18 Javascript
浅谈js中的引用和复制(传值和传址)
2016/09/18 Javascript
Java  Spring 事务回滚详解
2016/10/17 Javascript
jquery实现tab键进行选择后enter键触发click行为
2017/03/29 jQuery
vue-cli的webpack模板项目配置文件分析
2017/04/01 Javascript
纯js实现动态时间显示
2020/09/07 Javascript
js学使用setTimeout实现轮循动画
2017/07/17 Javascript
浅谈Vue-cli 命令行工具分析
2017/11/22 Javascript
javascript和php使用ajax通信传递JSON的实例
2018/08/21 Javascript
js 计数排序的实现示例(升级版)
2020/01/12 Javascript
vue实现div可拖动位置也可改变盒子大小的原理
2020/09/16 Javascript
ES6学习教程之Promise用法详解
2020/11/22 Javascript
可拖拽组件slider.js使用方法详解
2020/12/04 Javascript
Python开发的单词频率统计工具wordsworth使用方法
2014/06/25 Python
Python利用BeautifulSoup解析Html的方法示例
2017/07/30 Python
Django 导出 Excel 代码的实例详解
2017/08/11 Python
详解Python匿名函数(lambda函数)
2019/04/19 Python
Flask使用Pyecharts在单个页面展示多个图表的方法
2019/08/05 Python
详解Python3 中的字符串格式化语法
2020/01/15 Python
在Ubuntu 20.04中安装Pycharm 2020.1的图文教程
2020/04/30 Python
Virtualenv 搭建 Py项目运行环境的教程详解
2020/06/22 Python
详解python中GPU版本的opencv常用方法介绍
2020/07/24 Python
weblogic面试题
2016/03/07 面试题
UNIX特点都有哪些
2016/04/05 面试题
《中华少年》教学反思
2014/02/15 职场文书
学习“七一”讲话精神体会
2014/07/08 职场文书
干部作风建设个人剖析材料
2014/10/11 职场文书
机关作风建设剖析材料
2014/10/11 职场文书
2015年消防工作总结
2015/04/24 职场文书
Nginx反向代理、重定向
2022/04/13 Servers
vue封装数字翻牌器
2022/04/20 Vue.js