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爬虫之爬虫的定义及URL构成
Nov 04 Python
Python字符串特性及常用字符串方法的简单笔记
Jan 04 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
Python实现字符串反转的常用方法分析【4种方法】
Sep 30 Python
Python简单实现的代理服务器端口映射功能示例
Apr 08 Python
python实现按长宽比缩放图片
Jun 07 Python
Python3中关于cookie的创建与保存
Oct 21 Python
python hbase读取数据发送kafka的方法
Dec 27 Python
Windows系统Python直接调用C++ DLL的方法
Aug 01 Python
解决Python对齐文本字符串问题
Aug 28 Python
Python爬虫爬取杭州24时温度并展示操作示例
Mar 27 Python
python实现双人五子棋(终端版)
Dec 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
PHP 中英文混合排版中处理字符串常用的函数
2007/04/12 PHP
PHP实现类似于C语言的文件读取及解析功能
2017/09/01 PHP
javascript中的对象和数组的应用技巧
2007/01/07 Javascript
jquery ajax 登录验证实现代码
2009/09/23 Javascript
JS前端框架关于重构的失败经验分享
2013/03/17 Javascript
JS实现将人民币金额转换为大写的示例代码
2014/02/13 Javascript
jQuery使用正则表达式替换dom元素标签用法示例
2017/01/16 Javascript
深入理解Angularjs中$http.post与$.post
2017/05/19 Javascript
Angularjs中数据绑定的实例详解
2017/08/25 Javascript
微信通过页面(H5)直接打开本地app的解决方法
2017/09/09 Javascript
微信小程序实现添加手机联系人功能示例
2017/11/30 Javascript
jquery实现楼层滚动效果
2018/01/01 jQuery
jQuery实现上下滚动公告栏详细代码
2018/11/21 jQuery
JS无限级导航菜单实现方法
2019/01/05 Javascript
angular2 NgModel模块的具体使用方法
2019/04/10 Javascript
JS 5种遍历对象的方式
2020/06/16 Javascript
javascript中正则表达式语法详解
2020/08/07 Javascript
Python中使用Beautiful Soup库的超详细教程
2015/04/30 Python
Python3中使用PyMongo的方法详解
2017/07/28 Python
Python3多线程爬虫实例讲解代码
2018/01/05 Python
python安装gdal的两种方法
2019/10/29 Python
Python2与Python3的区别详解
2020/02/09 Python
使用python自动追踪你的快递(物流推送邮箱)
2020/03/17 Python
会计自我鉴定范文
2013/10/06 职场文书
网上卖盒饭创业计划书
2014/01/26 职场文书
幼儿园毕业园长感言
2014/02/24 职场文书
文体活动实施方案
2014/03/27 职场文书
任命书标准格式
2015/03/02 职场文书
社区重阳节活动总结
2015/03/24 职场文书
结婚通知短信大全
2015/04/17 职场文书
2015年电气技术员工作总结
2015/07/24 职场文书
班干部竞选演讲稿(精选5篇)
2019/09/24 职场文书
php中pcntl_fork详解
2021/04/01 PHP
python实现监听键盘
2021/04/26 Python
一篇文章带你搞懂Python类的相关知识
2021/05/20 Python
C站最全Python标准库总结,你想要的都在这里
2021/07/03 Python