1. Static methods are a common method, independent of classes and objects
2. The class method is the Java inside class method, belongs to the class, is shared by each object
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 ()
Running results are 5 and 0.
The static method is actually no different from the normal method, its argument list does not appear CLS, or self, to some extent, explain why it is class and object-Independent
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 ()
The result is 0, obviously self.count + = Origin_data is manipulating an object's properties rather than a class's properties.
Usually the method of class is easier to manipulate class attributes
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 ()
The result is 1 and 2, and class methods manipulate the CLS through the CLS
How do you modify a class variable in an instance method on a single object? Through 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 ()
The result is 122 and 122.