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 相关文章推荐
对变量赋值的理解--Pyton中让两个值互换的实现方法
Nov 29 Python
查看Django和flask版本的方法
May 14 Python
Python2.7.10以上pip更新及其他包的安装教程
Jun 12 Python
Python使用pickle模块储存对象操作示例
Aug 15 Python
python复制列表时[:]和[::]之间有什么区别
Oct 16 Python
python实现简单五子棋游戏
Jun 18 Python
Python_查看sqlite3表结构,查询语句的示例代码
Jul 17 Python
Python 保持登录状态进行接口测试的方法示例
Aug 06 Python
Pytorch中的自动求梯度机制和Variable类实例
Feb 29 Python
python如何发送带有附件、正文为HTML的邮件
Feb 27 Python
python引入其他文件夹下的py文件具体方法
May 23 Python
Python使用华为API为图像设置多个锚点标签
Apr 12 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
WebQQ最新登陆协议的用法
2014/12/22 PHP
PHP实现连接设备、通讯和发送命令的方法
2015/10/13 PHP
PHP设计模式之适配器模式定义与用法详解
2018/04/03 PHP
用JavaScript 处理 URL 的两个函数代码
2007/08/13 Javascript
IE6、IE7中获取Button元素的值的bug说明
2011/08/28 Javascript
浅析hasOwnProperty方法的应用
2013/11/20 Javascript
javascript中的作用域和上下文使用简要概述
2013/12/05 Javascript
使用js如何实现全选与全不选
2013/12/30 Javascript
nodejs中实现路由功能
2014/12/29 NodeJs
js实现图片和链接文字同步切换特效的方法
2015/02/20 Javascript
JS实现可直接显示网页代码运行效果的HTML代码预览功能实例
2015/08/06 Javascript
CascadeView级联组件实现思路详解(分离思想和单链表)
2016/04/12 Javascript
jQuery ztree实现动态树形多选菜单
2016/08/12 Javascript
require、backbone等重构手机图片查看器
2016/11/17 Javascript
JavaScript Canvas绘制圆形时钟效果
2020/08/20 Javascript
js针对图片加载失败的处理方法分析
2019/08/24 Javascript
微信小程序错误this.setData报错及解决过程
2019/09/18 Javascript
[16:43]Heroes19_剃刀(完美)
2014/10/31 DOTA
Python面向对象编程基础解析(二)
2017/10/26 Python
python执行系统命令后获取返回值的几种方式集合
2018/05/12 Python
python 用户交互输入input的4种用法详解
2019/09/24 Python
如何将tensorflow训练好的模型移植到Android (MNIST手写数字识别)
2020/04/22 Python
PyTorch-GPU加速实例
2020/06/23 Python
django前端页面下拉选择框默认值设置方式
2020/08/09 Python
解决python 执行shell命令无法获取返回值的问题
2020/12/05 Python
HTML5+lufylegend实现游戏中的卷轴
2016/02/29 HTML / CSS
编写strcpy函数
2014/06/24 面试题
DTD的含义以及作用
2014/01/26 面试题
大学生新闻专业个人自我评价
2013/11/12 职场文书
商场活动策划方案
2014/01/24 职场文书
销售冠军获奖感言
2014/02/03 职场文书
拓展训练激励口号
2014/06/17 职场文书
司法局2014法制宣传日活动总结
2014/11/01 职场文书
先进员工事迹材料
2014/12/20 职场文书
学校食堂食品安全承诺书
2015/04/29 职场文书
描述鲁迅的名言整理,一生受用
2019/08/08 职场文书