【发布时间】:2013-04-16 20:00:39
【问题描述】:
我知道他们在做什么,并且我已经看到了很多这两种方法的例子,但我还没有找到一个我必须使用 classmethod 而不是用 staticmethod 替换它的例子。
我见过的classmethod最常见的例子是为类本身创建一个新实例,像这样(非常简单的例子,没有使用atm方法。但是你明白了):
class Foo:
@classmethod
def create_new(cls):
return cls()
这将在调用foo = Foo.create_new() 时返回Foo 的新实例。
现在为什么我不能只使用它:
class Foo:
@staticmethod
def create_new():
return Foo()
完全一样,我为什么要使用classmethod 而不是staticmethod?
【问题讨论】:
标签: python class python-3.x static-methods class-method