Tag: method dispatch

什么时候应该使用@classmethod和def方法(self)?

在集成一个我以前没有用过的Django应用程序的时候,我发现了两种不同的用于在类中定义函数的方法。 作者似乎非常有意地使用它们。 第一个是我自己用的很多: class Dummy(object): def some_function(self,*args,**kwargs): do something here self is the class instance 另一个是我不使用的,主要是因为我不明白什么时候使用它,以及为什么: class Dummy(object): @classmethod def some_function(cls,*args,**kwargs): do something here cls refers to what? 在Python文档中, classmethod装饰classmethod这句话来解释: 类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。 所以我想cls是指Dummy本身( class ,而不是实例)。 我不完全明白为什么会这样,因为我总是可以这样做: type(self).do_something_with_the_class 这只是为了清楚起见,还是我错过了最重要的部分:没有它的事情是不可能做到的令人着迷和迷人的事情?