The difference between the difference between the static method python3 and self cls class and method

 


In general, to use a class, you need to instantiate an object and then call the method.

Or use @staticmethod @classmethod, you may not be required to instantiate, direct the class name. Method name () is invoked.

This facilitates the organization code, the function should belong to a certain class to go into that class, and help clean namespace

class A():
        a='1'

        @staticmethod
        def foo1(name):
                print("hello,%s"%(name))
        def foo2(self,name):
                print("hello,%s"%(name))

        @classmethod
        def foo3(cls,name):
                print("hello,%s"%(name))


a=A()
a.foo1('mamq')
A.foo1('mamq')
print("---------------------"*20)
a.foo2('mamq')
#A.foo2('mamq')

a.foo3('foo3')
A.foo3('foo3')

First, the definition of a class A, class A has three functions, foo1 static function, @staticmethod decorative decorator, this method has some relationship with the class, but do not need to participate in the class or instance. The following two methods can be normal output, that is to say the method may be used as a class, as an instance of a class may be a method to use.

  1.  
    a = A()
  2.  
    a.foo1 ( 'mamq')  # Output: hello mamq
  3.  
    A.foo1 ( 'mamq') # Output: hello mamq

foo2 normal function, is a function of the instance of the class, only through a call.

  1.  
    a.foo2 ( 'mamq')  # Output: hello mamq
  2.  
    A.foo2 ( 'mamq')  # error: this general class method can not be called 

foo3 class function, cls as the first parameter to represent the class itself. The method used in the class, the class method and is only unrelated to the method of Example class itself. The following two methods can be normally output.

  1.  
    a.foo3 ( 'mamq')  # Output: hello mamq
  2.  
    A.foo3 ( 'mamq')  # Output: hello mamq

 

 

After several tests the individual, currently found only class methods to prevent hardware decoding effect, in other cases, class methods can be replaced by a static method

 

 

Guess you like

Origin www.cnblogs.com/ZFBG/p/11459551.html