1.静态方法就是一个普通的方法,与类和对象无关
2.类方法就是JAVA里面的类方法,属于类,被各个对象共享
运行结果是5和0class 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()
静态方法其实和普通方法没什么差别,它的参数列表里面不会出现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