staticmethod与classmethod

2017-09-07  本文已影响0人  idri

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
上一篇下一篇

猜你喜欢

热点阅读