Python:staticmethod 和 classmethod的比较

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

内容简介:看一下输出:常规定义的方法: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...


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

查看所有标签

猜你喜欢:

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

Convergence Culture

Convergence Culture

Henry Jenkins / NYU Press / 2006-08-01 / USD 30.00

"Convergence Culture" maps a new territory: where old and new media intersect, where grassroots and corporate media collide, where the power of the media producer, and the power of the consumer intera......一起来看看 《Convergence Culture》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具