Python中staticmethod和classmethod的作用与区别
作者:斜阳雨陌 发布时间:2022-03-12 21:30:00
标签: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
=======================
"""
来源:https://blog.csdn.net/qq_15037231/article/details/77943109
0
投稿
猜你喜欢
- pytorch默认使用单精度float32训练模型,原因在于:使用float16训练模型,模型效果会有损失,而使用double(float6
- 随着网站访问量的加大,每次从数据库读取都是以效率作为代价的,很多用ACCESS作数据库的更会深有体会,静态页加在搜索时,也会被优先考虑。互联
- 今天开始学习 YUI,加强一下对 JavaScript 的理解。1. 命名空间 YAHOO
- 有些时候(如开发聊天程序),我们需要将将滚动条(scrollbar)保持在最底部,比如聊天窗口,最新发出和收到的信息要显示在最下方,如果要看
- 本文实例讲述了php简单获取复选框值的方法。分享给大家供大家参考,具体如下:html:<form id="form1&quo
- 在大型商业应用中,数据的异地容灾备份十分重要,也必不可少。笔者根据自己的实践经验,设计了一套简洁地实现异地数据自动备份的方法,可供数据库管理
- 1.MS SCRIPT ENCODE基本上没什么用了,一段JS就可以破解2.封装成DLL比较可行的方法,有通过VB封装成DLL的例子,而且无
- 内容摘要:当讨论Request对象内容时,要研究的集合之一就是ServerVariables集合。这个集合包含了两种值的结合体,一种是随同页
- 见以下两个文件:showimage.asp Change the HTTP header
- 项目有时要用一些Ajax的效果,因为比较简单,也就没有去用什么Ajax.net之类的东西,手写代码也就实现了。 第二天,有人反馈错
- 就MySQL而言,大多数程序员都不太了解其设计背景,因此当他们尝试创建自己的数据库时,会留下很多漏洞。要想为MySQL数据库进行合适的配置,
- #squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉#unsqueeze() 是squeeze()的反向操作
- 1、终极方法:条件注释<!--[if lte IE 6]> 这段文字仅显示在 IE6及IE6以下版本。 <![endif]
- 引用类型(Reference)在许多计算机语言中都被使用,而且是作为一个非常强大而实用的特性存在。它有类似指针(Pointer)的实现,却又
- 在 asp 应用中,经常用到 Session 对象来保存用户临时私有数据,而 asp 的 Session 对象是依赖于浏览器的 Cookie
- 为了画个图,被numpy这个模块的安装真的折腾疯了!!!一直装不上,花了几个小时,看了网上的很多教程、方法发现总结得不是很全,这里总结一下,
- 本文首先介绍在python3中print函数的应用,然后对比在pyhton2中的应用。(本文作者所用版本为3.6.0)首先我们通过help(
- 代码如下:< % Set fso=Server.CreateObject("Scripting
- 年前在重写淘宝旺铺里的会员卡脚本的时候,无意中发现了一个有趣的事情。代码类似:var associative_array = new Arr
- 如何在ASP.NET中使用ADO.NET连接数据库?以连接Access数据库为例,步骤如下:一、我们来用有源ODBC DSN的方法和无源OL