Python中@staticmethod和@classmethod的区别和用法

来源:互联网 发布:淘宝的美版iphone7渠道 编辑:程序博客网 时间:2024/06/05 07:17

Python其实有3类方法:

  • 静态方法(staticmethod)
  • 类方法(classmethod)
  • 实例方法(instance method)

常规方式, @classmethod修饰方式, @staticmethod修饰方式.

def foo(x):    print "executing foo(%s)" %(x)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)" %xa = A()


1. 绑定的对象
foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定。

2. 调用方式
/实例方法类方法静态方法a = A()a.foo(x)a.class_foo(x)a.static_foo(x)A不可用
A.clas_foo(x)A.static_foo(x)
3. classmethod和staticmethod的区别
直观上看,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):     passclass Girl(Parent):    passif __name__ == '__main__':    Boy.classSayHello()    Girl.classSayHello()

原创粉丝点击