静态方法(@staticmethod)和类方法(@classmethod)都是类中的特殊方法,他们都可以通过类直接调用而无需先实例化。他们的区别可用Stack Overflow上面的回答来简单解释:
image.png
静态方法只和一个类(就像一个类变量)相关联,而不是一个具体的类实例。
简单来说就是类方法(@classmethod)在定义时第一个参数必须是类对象,而静态方法(@staticmethod)第一个参数则无需是实例对象(self)或类对象。
class A(object):
#一般的类方法,第一个参数需要传入实例对象(self)
def normalMethod(self, arg):
print(arg)
#类方法,第一个参数需要传入类对象(即为此处的cls)
@classmethod
def classMethod(cls, arg):
print(arg)
#静态方法,无需传入实例对象或类对象
@staticmethod
def staticMethod(arg):
print(arg)
a = A()
arg = 'hello world!'
a.normalMethod(arg)
A.staticMethod(arg)
A.classMethod(arg)
#输出
hello world!
hello world!
hello world!
###############################################################
###############################################################
#类里面调用方式
class A(object):
def __init__(self, arg):
self.arg = arg
@classmethod
def p(cls, arg):
print('classmethod: ', arg)
@staticmethod
def pp(arg):
print('staticmethod: ', arg)
def f(self):
arg = self.arg
self.p(arg)
self.pp(arg)
a = A('hello world.')
a.f()
a.p('hohohohoho')
A.pp('hahahaha')
#输出
classmethod: hello world.
staticmethod: hello world.
classmethod: hohohohoho
staticmethod: hahahaha