Python @staticmethod@classmethod用法

参考链接:https://blog.csdn.net/sinat_34079973/article/details/53502348

一般来说,调用某个类的方法,需要先生成一个实例,再通过实例调用方法。Java中有静态变量,静态方法,可以使用类直接进行调用。Python提供了两个修饰符@staticmethod @classmethod也可以达到类似效果。

@staticmethod 声明方法为静态方法,直接通过 类||实例.静态方法()调用。经过@staticmethod修饰的方法,不需要self参数,其使用方法和直接调用函数一样。

#直接定义一个test()函数
def test():
    print "i am a normal method!"
#定义一个类,其中包括一个类方法,采用@staticmethod修饰    
class T:

    @staticmethod
    def static_test():#没有self参数
        print "i am a static method!"

if __name__ == "__main__":
    test()
    T.static_test()
    T().static_test()

output:
i am a normal method!
i am a static method!
i am a static method!      
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

@classmethod声明方法为类方法,直接通过 类||实例.类方法()调用。经过@classmethod修饰的方法,不需要self参数,但是需要一个标识类本身的cls参数。

class T:
    @classmethod
    def class_test(cls):#必须有cls参数
        print "i am a class method"
if __name__ == "__main__":
    T.class_test()
    T().class_test()

output:
i am a class method
i am a class method   
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

从上面的代码片可以看出@staticmethod @classmethod的用法,引申出一个话题,Python定义函数时候是否需要self参数。
定义一个普通函数,不需要self参数

def test():
    print "i am a test method!"
调用方法
    test()
  
  
  • 1
  • 2
  • 3
  • 4

定义一个类的实例方法,需要self参数

1.不加self参数
class T:
    def test():#不加self参数
        print "i am a normal method!"
调用
t = T()
t.test()
output: #test()方法不需要参数,但是传入了参数
Traceback (most recent call last):
  File "F:/Workspace/test_script/test.py", line 28, in <module>
    T().test()
TypeError: test() takes no arguments (1 given)

实际上t.test() 调用方法为T.test(t)实际上是把实例当作参数传给方法。故self方法不可缺失。
2.加self参数
class T:
    def test(self):
        print "self content is %s" % self
        print "i am a normal method!"
调用
t = T()
t.test()
output: 

self content is <__main__.T instance at 0x025F14B8>#self为T的实例
i am a test normal
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

定义一个类的静态方法,不需要self参数
定义一个类方法,需要cls参数

小结:在Python中类和实例都是对象,都占用了内存空间,合理的使用@staticmethod @classmethod方法,就可以不实例化就直接使用类的方法啦~~

一般来说,调用某个类的方法,需要先生成一个实例,再通过实例调用方法。Java中有静态变量,静态方法,可以使用类直接进行调用。Python提供了两个修饰符@staticmethod @classmethod也可以达到类似效果。

猜你喜欢

转载自blog.csdn.net/qq_26369907/article/details/88824385