Examples of methods, static methods and class distinction method

 

class A:
 # instance method: 
  DEF F1 (Self):
     return . 1
 # class methods: 
  @classmethod
   DEF F2 (CLS):
     return 2
 # static method 
  @staticmethod
   DEF F3 ():
     return . 3 
 
A = A () 
 
a.f1 ( ) # =>. 1 
A.f1 (A) # =>. 1 
a.f2 () # => 2 
A.f2 () # => 2 
a.f3 () # =>. 3 
A.f3 () # => 3
  • Instance method (also known as members of the method used to describe the intrinsic behavior of the object): The current default instance of an object is passed as the first argument
  • Method class (class method defining, in the above method must be added @classmethod ): the current default class as the first parameter passed
  • Static methods (static methods when defining the method must be added on top @staticmethod ): The first argument is no default

Examples of method invocation format:

  Object name. Method name ()

Method invocation format:

  Class name. Method name (parameter) recommended method

  Object name. Method name (argument) is not recommended

note:

(1) class method is defined in Le kinds of behavior does not belong to a specific object, it can be used in common for all objects behavior

(2) class methods are not allowed in instance variables and instance methods, instance methods allow the use of class variables and class methods, it is recommended to use the class name calling

(3) Examples of the method allows the use of class variables and class methods

Static method call format:

  Class name. Method name (arguments) recommended

  Object name. Method name (argument) is not recommended

Guess you like

Origin www.cnblogs.com/maplethefox/p/11615190.html