Python中staticmethod和classmethod的作用与区别

 更新时间:2018年10月11日 09:46:42   作者:斜阳雨陌  
今天小编就为大家分享一篇关于Python中staticmethod和classmethod的作用与区别,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。

而使用@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 pymysql操作MySQL详细

    Python pymysql操作MySQL详细

    pymysql是Python3.x中操作MySQL数据库的模块,其兼容于MySQLdb,使用方法也与MySQLdb几乎相同,但是性能不如MySQLdb,但是由于其安装使用方便、对中文兼容性也更好等优点,被广泛使用。可以使用pip install pymysql进行安装。
    2021-09-09
  • matplotlib 使用 plt.savefig() 输出图片去除旁边的空白区域

    matplotlib 使用 plt.savefig() 输出图片去除旁边的空白区域

    这篇文章主要介绍了matplotlib 使用 plt.savefig() 输出图片去除旁边的空白区域,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Python任务调度模块APScheduler使用

    Python任务调度模块APScheduler使用

    这篇文章主要介绍了Python任务调度模块APScheduler使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • 利用python和ffmpeg 批量将其他图片转换为.yuv格式的方法

    利用python和ffmpeg 批量将其他图片转换为.yuv格式的方法

    今天小编就为大家分享一篇利用python和ffmpeg 批量将其他图片转换为.yuv格式的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python使用Flask框架获取当前查询参数的方法

    Python使用Flask框架获取当前查询参数的方法

    这篇文章主要介绍了Python使用Flask框架获取当前查询参数的方法,实例分析了query_string获取查询参数的技巧,需要的朋友可以参考下
    2015-03-03
  • python 6种方法实现单例模式

    python 6种方法实现单例模式

    这篇文章主要介绍了python 6种方法实现单例模式,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2020-12-12
  • python 实现两个变量值进行交换的n种操作

    python 实现两个变量值进行交换的n种操作

    这篇文章主要介绍了python 实现两个变量值进行交换的n种操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • opencv实现简单人脸识别

    opencv实现简单人脸识别

    这篇文章主要为大家详细介绍了opencv实现简单人脸识别,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-08-08
  • python光学仿真面向对象光学元件类的实现

    python光学仿真面向对象光学元件类的实现

    这篇文章主要为大家介绍了python光学仿真面向对象光学元件类的实现示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2021-10-10
  • Python利用lxml模块爬取豆瓣读书排行榜的方法与分析

    Python利用lxml模块爬取豆瓣读书排行榜的方法与分析

    这篇文章主要给大家介绍了关于Python爬虫利用lxml模块爬取豆瓣读书排行榜的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-04-04

最新评论