python中类方法和静态方法的区别_python中静态方法和类方法的区别

1.静态方法就是一个普通的方法,与类和对象无关

2.类方法就是JAVA里面的类方法,属于类,被各个对象共享

class OptSample(object):

count = 0

def __init__(self,origin_data):

self.origin_data = origin_data

@staticmethod

def add_number(num1,num2):

print(num1 + num2)

@classmethod

def total(cls):

print(cls.count)

sample1 = OptSample(1)

sample2 = OptSample(2)

sample1.add_number(2,3)

sample1.total()运行结果是5和0

静态方法其实和普通方法没什么差别,它的参数列表里面不会出现cls,或者self,在一定程度上解释了为什么它是类和对象无关的

class OptSample(object):

count = 0

def __init__(self,origin_data):

self.origin_data = origin_data

self.count += origin_data

@classmethod

def total(cls):

print(cls.count)

sample1 = OptSample(1)

sample1.total()

结果是0,很明显

self.count += origin_data

是在操作一个对象的属性而非一个类的属性,

通常在类的方法较容易操作类属性

class OptSample(object):

count = 0

def __init__(self,origin_data):

self.origin_data = origin_data

@classmethod

def total(cls):

cls.count += 1

print(cls.count)

sample1 = OptSample(1)

sample1.total()

OptSample.total()结果是1和2,类方法通过cls来操作cls

那么就单个对象而言如何在实例方法中去修改类变量?通过self.__class__

class OptSample(object):

count = 0

def __init__(self,origin_data):

self.origin_data = origin_data

self.__class__.count += origin_data

@classmethod

def total(cls):

print(cls.count)

sample1 = OptSample(122)

sample1.total()

OptSample.total()结果是122和122

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值