Python种staticmethod和classmethod有什么区别,具体用法呢。什么时候用。

抱歉,问题可能很小白,但是实在不明白,求助下。网上看了好几个例子,都看不懂

class Person:

    def __init__(self):
        print "init"

    @staticmethod
    def sayHello(hello):
        if not hello:
            hello='hello'
        print "i will sya %s" %hello


    @classmethod
    def introduce(cls,hello):
        cls.sayHello(hello)
        print "from introduce method"

    def hello(self,hello):
        self.sayHello(hello)
        print "from hello method"
        
        

我的理解是加了@staticmethod之后,直接可以Person.sayHello("mimi")就出效果了,而不用p=Person()去创建实例。可这样有什么用呢。具体什么时候需要这样呢。

@classmethod,需要传入第一个参数是本class,也是不用创建instance就可以用。可这样有什么用呢。具体什么时候需要这样呢。

实在不明白~~~希望有大神来解答下。

阅读 9.7k
6 个回答

staticmethod并不是因为不想创建实例才声明的,而是声明该方法不会更改实例本身的数据。

classmethod也并不是因为不想创建实例才声明的,而是为了实现对类本身的操作(传入cls之后就可以对自身的属性和方法进行操作)。

仅仅是个人浅薄的见解,供题主参考一下。

直观上看,classmethod和staticmethod的函数签名不一样,一个是有参的,一个是无参的。
都属于python的装饰器,注意在classmethod里,参数不一定必须是cls,可以是任何命名的变量。在不涉及到父子类的时候,这2者行为看起来是一样的,但如果设计到父子类的时候,classmethod可以判断出调用的子类对象

# -*- coding: utf-8 -*-

class Parent(object):

    @staticmethod
    def staticSayHello():
        print "Parent static"

    @classmethod
    def classSayHello(anything):  #这里是anything
        if anything == Boy:
            print "Boy classSayHello"
        elif anything == Girl:
            print "girl sayHello"


class Boy(Parent):
     pass

class Girl(Parent):
    pass

if __name__ == '__main__':
    Boy.classSayHello()
    Girl.classSayHello()

static 和 class 还有 普通的内部方法的区别除了用法上的细微区别 主要还是考虑到代码隔离上。static 不需要任何类和实例的信息。 class 需要类的信息。 普通方法需要 instance 实例信息。不用太在意这些细节。当你不明白的时候都写成普通方法好了。当你感觉到有需要的时候你就知道改用哪个了。

Python2.7(Python3中与这个有点不同)
class A(object):
    @staticmethod
    def staticMethod():
        return 'static method'
    @classmethod
    def classMethod(cls):  #此处的cls必须要,某种形式上的吧(见后面)
        #cls到底是什么,测试一下
        print cls
        return 'class method'
        
a = A()
a.staticMehtod()  #ok
A.staticMehtod() #ok
a.classMethod()  #ok
A.classMethod()  #ok

[总结]:
classmethod就是类方法,跟着类走(不是实例),staticmethod类似于恰好放在类中的一个局部函数(不是方法),非常像类方法
staticmethod处理一个类的本地数据,classmethod处理类层级中属于类的数据
[总结]
好像没有什么很大的不同,楼主看感觉用吧,语法别搞错了.
另外在Python3中,这些东西就好多了,没有2中这么多唧唧歪歪的东西.

在一门面向对象对象语言中,static通常意味着被修饰的方法或者变量不属于实例,而是属于类。

静态方法的作用在于:如何一个方法需要在不构造实例的情况下调用,那么这个方法就需要被定义成静态。静态方法不能被override,也不具备大部分OO特性,静态方法实际上存在过程式语言的思想。

根据自己写Python代码的经验,面向对象在Python中用起来有点生硬,比如static方法和函数不知道选择谁。所以,建议专注学习Python自己独特的特性,而不是OO。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题