具体详情,请看参考链接!
写与类进行交互的方法,而不是实例。
@classmethod:
使用地方:
和类进行交互,但不和其实例进行交互的函数方法
举个例子:
class ClassandStaticMethod(object):
value = "get the value without instance"
def __init__(self,data):
self.data = data
def InteractClassWithoutInstance(cls):
return cls.value+" added successfuly"
print InteractClassWithoutInstance(ClassandStaticMethod)
#result
>get the value without instanceadded successfuly
class ClassandStaticMethod(object):
value = "get the value without instance"
def __init__(self,data):
self.data = data
@classmethod
def InteractClassWithoutInstance(cls):
return cls.value+" added successfuly"
print ClassandStaticMethod.InteractClassWithoutInstance()
#instance
#也可以实例化之后使用该函数。
cs = ClassandStaticMethod("Jack")
print cs.InteractClassWithoutInstance()
#result
> get the value without instance added successfuly
get the value without instance added successfuly
@staticmethod:
使用地方:
有一些和类相关函数,但不要使用该类或者该类的实例;比如更改环境变量或者修改其他类的属性等。
class ClassandStaticMethod(object):
value = "get the value without instance"
def __init__(self,data):
self.data = data
@classmethod
def InteractClassWithoutInstance(cls):
return cls.value+" added classmethod successfuly"
@staticmethod
def set_variable(value):
return value+" added successfuly "
print ClassandStaticMethod.InteractClassWithoutInstance()
print ClassandStaticMethod.set_variable("staticmethod")
#instance
cs = ClassandStaticMethod("Jack")
print cs.InteractClassWithoutInstance()
print cs.set_variable("staticmethod_2")
#result
>
get the value without instance added classmethod successfuly
staticmethod added successfuly
get the value without instance added classmethod successfuly
staticmethod_2 added successfuly
示例二:
class Kls(object):
def __init__(self, data):
self.data = data
def printd(self):
print(self.data)
@staticmethod
def smethod(*arg):
print('Static:', arg)
@classmethod
def cmethod(*arg):
print('Class:', arg)
Kls.smethod(1,2,4)
Kls.cmethod(1,2,5)
ik = Kls(123)
ik.smethod(1,2,4)
ik.cmethod(1,2,5)
#result
>
('Static:', (1, 2, 4))
('Class:', (<class '__main__.Kls'>, 1, 2, 5))
('Static:', (1, 2, 4))
('Class:', (<class '__main__.Kls'>, 1, 2, 5))
notice: classmethod需要一个对类的引用作为第一个参数,而staticmethod不需要。
ref: