python 类中@staticmethod,@classmethod和实例方法

来源:互联网 发布:网络交换机的安装 编辑:程序博客网 时间:2024/06/05 20:49

一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法(类中的实例方法)。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。


在类方法中,实例方法相信大家都经常使用,所以这里不再赘余。

@staticmethod和@classmethod方法的区别如下:

从它们的使用上来看,

  • @staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
  • @classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名().方法名()。
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。


代码如下:

class Method(object):        method = u"三种方法的比较"        def instance_method(self):        print u"正在调用实例方法"        @classmethod    def class_method(cls):        print u"正在调用类方法"        print u"在类方法中调用类属性method\t{}".format(cls.method)        print u"在类方法中调用实例方法\t",         cls().instance_method()        @staticmethod    def static_method():        print u"正在调用静态方法"        print u"在静态方法中调用实例方法",        Method().instance_method()        print u"在静态方法中调用类属性method\t%s" % Method.method        @classmethod    def class_method1(cls, num):        print num        @staticmethod    def static_method1(num):        print numif __name__ == "__main__":    Method.static_method()    print u"-" * 16    Method.class_method()    print u"-" * 16    # 带参数传递的情况如下    Method.static_method1(2017)    print u"-" * 16    Method.class_method1(2017)"""输出结果如下:正在调用静态方法在静态方法中调用实例方法 正在调用实例方法在静态方法中调用类属性method三种方法的比较----------------正在调用类方法在类方法中调用类属性method三种方法的比较在类方法中调用实例方法正在调用实例方法----------------2017----------------2017"""


阅读全文
0 0
原创粉丝点击