Python 中的 classmethod 和 staticmethod 有什么具体用途?

来源:互联网 发布:什么是原型软件 编辑:程序博客网 时间:2024/04/27 19:02
http://www.zhihu.com/question/20021164
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())

用了@classmethod修饰以后,cls_obj就是直接获取到Kls这个class,相当于自动将Kls这个class作为参数传给get_no_of_instance方法了。

去掉@classmethod修饰的话,第一个print是ok的,输出了一个2

但是第二个print就不行了。
提示get_no_of_instance方法缺少参数。

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).


感觉这段话说的不错,看第一句,如果这个方法被called,正常的话会将class的instance作为first argument传给method,所以第一个print成功了,cls_obj获得了传进来的instance of class,就是ik1,。而第二个print里面,由于call这个method时class没有instance,所以method的参数就为空,然后就报错了。如果我们用了@classmethod修饰以后,就不按正常走,不传instance了,而是传class,所以估计两个print都会成功,结果应该是两个2
OK,正确的。

再看看@staticmethod,就是说method被call的时候,instance of class不会被传给method。嗯,这样我们就可以传参数给cls_obj了?试试看
首先试试出错场景
然后正常情况传个参数给method,可以看到python自己就会传一个instance作为first argument,我再传一个3过去就出错了。
加入@staticmethod然后再传参数,那就正确了。
0 0
原创粉丝点击