美文网首页
staticmethod与classmethod

staticmethod与classmethod

作者: idri | 来源:发表于2017-09-07 14:35 被阅读0次

    https://www.zhihu.com/question/20021164
    https://link.zhihu.com/?target=http%3A//www.pythoncentral.io/difference-between-staticmethod-and-classmethod-in-python/

    类方法和静态方法都可以被类和类实例调用,类实例方法仅可以被类实例调用

    classmethod

    类方法:类可以直接调用@classmethod装饰的方法,无需实例化。
    特点:参数需要传递类,可以访问类属性,不创建实例,即不访问'init'

    静态方法:没有参数,更改环境变量或者修改其他类的属性等能用到静态方法。不用传递类或者类的实例。

    # coding: utf-8
    class Kls(object):
        no_inst = 0
        def __init__(self):
            Kls.no_inst = Kls.no_inst + 1
        @classmethod
        def get_no_of_instance(cls_obj):
            return cls_obj.no_inst
    ik1 = Kls()
    ik2 = Kls()
    print ik1.get_no_of_instance()
    print Kls.get_no_of_instance()
    
    print Kls().no_inst
    print Kls().no_inst
    # 输出:
    # 2
    # 2
    # 3
    # 4
    

    相关文章

      网友评论

          本文标题:staticmethod与classmethod

          本文链接:https://www.haomeiwen.com/subject/vidijxtx.html