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程序与服务器连接的WSGI接口
Apr 29 Python
Python安装官方whl包和tar.gz包的方法(推荐)
Jun 04 Python
python读取excel表格生成erlang数据
Aug 26 Python
详谈python read readline readlines的区别
Sep 22 Python
python中装饰器级连的使用方法示例
Sep 29 Python
对Python字符串中的换行符和制表符介绍
May 03 Python
浅谈Python批处理文件夹中的txt文件
Mar 11 Python
pycharm修改文件的默认打开方式的步骤
Jul 29 Python
python与mysql数据库交互的实现
Jan 06 Python
Python面向对象程序设计之静态方法、类方法、属性方法原理与用法分析
Mar 23 Python
Python如何实现爬取B站视频
May 20 Python
python读取并查看npz/npy文件数据以及数据显示方法
Apr 14 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
zend api扩展的php对象的autoload工具
2011/04/18 PHP
php session安全问题分析
2011/06/24 PHP
使用php 获取时间今天明天昨天时间戳的详解
2013/06/20 PHP
php curl获取网页内容(IPV6下超时)的解决办法
2013/07/16 PHP
PHP使用feof()函数读文件的方法
2014/11/07 PHP
PHP中if和or运行效率对比
2014/12/12 PHP
PHP统计当前在线用户数实例讲解
2015/10/21 PHP
使用PHP实现下载CSS文件中的图片
2015/12/06 PHP
Symfony的安装和配置方法
2016/03/17 PHP
浅析php-fpm静态和动态执行方式的比较
2016/11/09 PHP
Yii2.0建立公共方法简单示例
2019/01/29 PHP
基于JQuery的模拟苹果桌面Dock效果(稳定版)
2012/10/15 Javascript
JavaScript打印网页指定区域的例子
2014/05/03 Javascript
用队列模拟jquery的动画算法实例
2015/01/20 Javascript
javascript内置对象操作详解
2015/02/04 Javascript
JavaScript调用传递变量参数的相关问题及解决办法
2015/11/01 Javascript
javascript判断图片是否加载完成的方法推荐
2016/05/13 Javascript
Javascript中indexOf()和lastIndexOf应用方法实例
2016/08/24 Javascript
bootstrap与Jquery UI 按钮样式冲突的解决办法
2016/09/23 Javascript
vue.js表格分页示例
2016/10/18 Javascript
jQuery实现圣诞节礼物传送(花式轮播)
2016/12/25 Javascript
vue+eslint+vscode配置教程
2019/08/09 Javascript
Python中变量交换的例子
2014/08/25 Python
python 爬取微信文章
2016/01/30 Python
Python表示矩阵的方法分析
2017/05/26 Python
TensorFlow高效读取数据的方法示例
2018/02/06 Python
[原创]windows下Anaconda的安装与配置正解(Anaconda入门教程)
2018/04/05 Python
浅谈pycharm的xmx和xms设置方法
2018/12/03 Python
对pandas通过索引提取dataframe的行方法详解
2019/02/01 Python
一篇文章弄懂Python中所有数组数据类型
2019/06/23 Python
解决Python中报错TypeError: must be str, not bytes问题
2020/04/07 Python
Python创建文件夹与文件的快捷方法
2020/12/08 Python
意大利奢侈品网站:Italist
2016/08/23 全球购物
珍珠奶茶店创业计划书
2014/01/11 职场文书
社区党务公开实施方案
2014/03/18 职场文书
手残删除python之后的补救方法
2021/06/26 Python