您的位置:首页 > 编程语言 > Python开发

理解python:@classmethod 和@staticmethod

2016-11-29 18:42 387 查看
具体详情,请看参考链接!

用途:

写与类进行交互的方法,而不是实例。

@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


使用@classmethod的方式:

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:

http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner

http://pythoncentral.io/difference-between-staticmethod-and-classmethod-in-python/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: