作者:李保银
链接:https://www.zhihu.com/question/20021164/answer/18224953
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

普通方法,静态方法和类方法

这个答案的原文是Difference between @staticmethod and @classmethod in Python
这里的内容是我通知原作者并得到允许的情况下的翻译稿
这个是我的博客文章的地址pyhton静态方法和类方法
类中最常用的方法是实例方法, 即通过通过实例作为第一个参数的方法。
举个例子,一个基本的实例方法就向下面这个:


class Kls(object): def __init__(self, data): self.data = data def printd(self): print(self.data) ik1 = Kls('arun') ik2 = Kls('seema') ik1.printd() ik2.printd() 

这会给出如下的输出:
arun
seema

<img src="https://pic4.zhimg.com/50/a2173bce20299607befc10abf8c7041b_hd.jpg" data-rawwidth="372" data-rawheight="322" class="content_image" width="372">

然后看一下代码和示例图片:

  • 1,2参数传递给方法.
  • 3 self参数指向当前实例自身.
  • 4 我们不需要传递实例自身给方法,Python解释器自己会做这些操作的.

如果现在我们想写一些仅仅与类交互而不是和实例交互的方法会怎么样呢? 我们可以在类外面写一个简单的方法来做这些,但是这样做就扩散了类代码的关系到类定义的外面. 如果像下面这样写就会导致以后代码维护的困难:


def get_no_of_instances(cls_obj): return cls_obj.no_inst class Kls(object): no_inst = 0 def __init__(self): Kls.no_inst = Kls.no_inst + 1 ik1 = Kls() ik2 = Kls() print(get_no_of_instances(Kls)) 

输出:
2
@classmethod
我们要写一个只在类中运行而不在实例中运行的方法. 如果我们想让方法不在实例中运行,可以这么做:


def iget_no_of_instance(ins_obj): return ins_obj.__class__.no_inst class Kls(object): no_inst = 0 def __init__(self): Kls.no_inst = Kls.no_inst + 1 ik1 = Kls() ik2 = Kls() print iget_no_of_instance(ik1) 

输出
2
在Python2.2以后可以使用@classmethod装饰器来创建类方法.


class Kls(object): no_inst = 0 def __init__(self): Kls.no_inst = Kls.no_inst + 1 @classmethod def get_no_of_instance(cls_obj): return cls_obj.no_inst ik1 = Kls() ik2 = Kls() print ik1.get_no_of_instance() print Kls.get_no_of_instance() 

输出:
2
2
这样的好处是: 不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来.
@staticmethod
经常有一些跟类有关系的功能但在运行时又不需要实例和类参与的情况下需要用到静态方法. 比如更改环境变量或者修改其他类的属性等能用到静态方法. 这种情况可以直接用函数解决, 但这样同样会扩散类内部的代码,造成维护困难.
比如这样:


IND = 'ON'
def checkind(): return (IND == 'ON') class Kls(object): def __init__(self,data): self.data = data def do_reset(self): if checkind(): print('Reset done for:', self.data) def set_db(self): if checkind(): self.db = 'new db connection' print('DB connection made for:',self.data) ik1 = Kls(12) ik1.do_reset() ik1.set_db() 

输出:
Reset done for: 12
DB connection made for: 12
如果使用@staticmethod就能把相关的代码放到对应的位置了.


IND = 'ON'
class Kls(object): def __init__(self, data): self.data = data @staticmethod def checkind(): return (IND == 'ON') def do_reset(self): if self.checkind(): print('Reset done for:', self.data) def set_db(self): if self.checkind(): self.db = 'New db connection' print('DB connection made for: ', self.data) ik1 = Kls(12) ik1.do_reset() ik1.set_db() 

输出:
Reset done for: 12
DB connection made for: 12
下面这个更全面的代码和图示来展示这两种方法的不同
@staticmethod 和 @classmethod的不同


class Kls(object): def __init__(self, data): self.data = data def printd(self): print(self.data) @staticmethod def smethod(*arg): print('Static:', arg) @classmethod def cmethod(*arg): print('Class:', arg) >>> ik = Kls(23) >>> ik.printd() 23 >>> ik.smethod() Static: () >>> ik.cmethod() Class: (<class '__main__.Kls'>,) >>> Kls.printd() TypeError: unbound method printd() must be called with Kls instance as first argument (got nothing instead) >>> Kls.smethod() Static: () >>> Kls.cmethod() Class: (<class '__main__.Kls'>,) 

下面这个图解释了以上代码是怎么运行的:
&amp;amp;lt;img src="https://pic3.zhimg.com/50/8a82a7f295c855c39b0d21f5bb1352c2_hd.jpg" data-rawwidth="563" data-rawheight="324" class="origin_image zh-lightbox-thumb" width="563" data-original="https://pic3.zhimg.com/8a82a7f295c855c39b0d21f5bb1352c2_r.jpg"&amp;amp;gt;

转载于:https://www.cnblogs.com/wangmo/p/7772982.html

Python 中的 classmethod 和 staticmethod 有什么具体用途?相关推荐

  1. [转载] python staticmethod有什么意义_Python 中的 classmethod 和 staticmethod 有什么具体用途

    参考链接: Python staticmethod() >>> type(a1) example 2: class a(object): @classmethod def cm(cl ...

  2. python中的@classmethod的作用

    推荐 <Python 中的 classmethod 和 staticmethod 有什么具体用途?> 一.简介 1.1 描述 classmethod 修饰符对应的函数不需要实例化,不需要 ...

  3. python classmethod_对Python中的@classmethod用法详解

    在Python面向对象编程中的类构建中,有时候会遇到@classmethod的用法. 总感觉有这种特殊性说明的用法都是高级用法,在我这个层级的水平中一般是用不到的. 不过还是好奇去查了一下. 大致可以 ...

  4. 关于Python中的classmethod

    Python 中的 classmethod classmethod: 作用是直接将自己的类对象,传给类方法. 一.classmethod 1)不用classmethod的时候 你的代码可能是这样写的, ...

  5. python知识:@classmethod和@staticmethod的异同

    1 说明 @staticmethod的意思就是将后面的函数转化成静态函数. 大多数情况,@classmethod和@staticmethod效果一样.但是那不是正题,正式作用是类工厂,如果有类继承关系 ...

  6. Python中的@classmethod修饰符

    classmethod修饰符对应的函数不需要实例化,不需要self参数,但第一个参数需要是表示自身类的cls参数,可以来调用类的属性,类的方法,实例化对象等 class A(object):bar = ...

  7. python中静态变量和静态方法_【开发者笔记】python中的类方法(@classmethod)和静态方法(@staticmethod)...

    在java.c#等高级语言中我们用static来定义静态方法和静态变量,那么在python中如何定义静态方法和静态变量呢. python提供了@classmethod和@staticmethod来定义 ...

  8. python中superclass是什么_Python中super()函数简介及用法分享

    首先看一下super()函数的定义: super([type [,object-or-type]]) Return a **proxy object** that delegates method c ...

  9. Python中super()函数简介及用法分享

    首先看一下super()函数的定义: super([type [,object-or-type]]) Return a **proxy object** that delegates method c ...

  10. python中@staticmethod、@classmethod和实例方法

    1.形式上的异同点: 在形式上,Python中:实例方法必须有self,类方法用@classmethod装饰必须有cls,静态方法用@staticmethod装饰不必加cls或self,如下代码所示: ...

最新文章

  1. android 开发 命名规范
  2. python sqlsever 时间_Python sqlalchemy时间戳及密码管理实现代码详解
  3. 百兆光纤收发器和千兆光纤收发器的区别
  4. 求数字序列中的第n位对应的数字
  5. 怎样快速画出一个正方体_小学数学非常有效的“画图”解题法,快速解题的“金钥匙”...
  6. TensorFlow是什么?TensorFlow入门与实践 架构与设计详解
  7. WORDPRESS”丢失计划任务”
  8. 一个人的命运决定于晚上8点到10点之间...
  9. android学习笔记---60_meta-data的使用,在清单文件中是用meta-data来给activity,service,receiver提供参数
  10. vue可以直接进行运算么_Vue实现手机计算器
  11. CSS 滤镜学习小结
  12. 新书介绍:CCNA基础教程
  13. 一款基于VUE3.0的开源卡密发卡系统
  14. chrome安装油猴插件
  15. PayPal提现到美国账户收35美元怎么办?最新3种解决办法!
  16. Introduce·艺术学超级友好必投普通期刊推荐之《戏剧之家》
  17. 计算机辅助翻译实践语料库,《计算机辅助翻译实践》
  18. 在线答题系统(小型HTTP服务器)
  19. r语言查找是否存在空值_R语言读取数据空值
  20. echarts的xAxis的type=’time’

热门文章

  1. JAVA中public protected default private访问权限
  2. esayUI实践的一些体会
  3. 阿里云--域名,主机,备案都配置好了,就是不能访问网站的解决方案
  4. BigPipe为什么可以节省时间?
  5. nginx-0.1.0文件分析2: ngx_socket.c
  6. CAS配置数据库进行用户验证
  7. SQL SERVER: 合并相关操作(Union,Except,Intersect)
  8. js正则表达式--个人常用
  9. js时间对象相关函数
  10. 慕课网仿去哪儿项目笔记--(五)-详情页面的开发