理解python:@classmethod 和@staticmethod

具体详情,请看参考链接!

用途:

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

@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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值