Python:staticmethod 和 classmethod的比较

栏目: Python · 发布时间: 7年前

内容简介:看一下输出:常规定义的方法:classmethod的输出:
class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()

看一下输出:

常规定义的方法:

a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)

classmethod的输出:

a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

以上代码可以看出,创建classmethod时,该对象实例的class cls 是作为第一个输入变量的,而不是该实例本身(如果是实例本身的话,第一个输入变量就是 self , 就是一个普通的我们常用的情况了)

这样创建的classmethod 有什么好处呢? 好处就是你可以直接用class来call这个函数,而不需要费周折地先去创建一个实例(class instance)。

而staticmethods呢,它没有默认的第一个输入变量。 它跟我们在一个空白的script里写的一个普通的函数 def fund():... 没有任何实质的区别。唯一的不同就是你要通过 类 class 或者实例 instance 来call它。

With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class.

本文参考来源: https://stackoverflow.com/que...


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Windows黑客编程技术详解

Windows黑客编程技术详解

甘迪文 / 人民邮电出版社 / 2018-12 / 108

《Windows黑客编程技术详解》介绍的是黑客编程的基础技术,涉及用户层下的Windows编程和内核层下的Rootkit编程。本书分为用户篇和内核篇两部分,用户篇包括11章,配套49个示例程序源码;内核篇包括7章,配套28个示例程序源码。本书介绍的每个技术都有详细的实现原理,以及对应的示例代码(配套代码均支持32位和64位Windows 7、Windows 8.1及Windows 10系统),旨在......一起来看看 《Windows黑客编程技术详解》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具