Summary of Differences between python Functions and Methods

  • 2021-06-29 11:34:40
  • OfStack

(1) Classification of functions:

Built-in functions: Some functions embedded in python.

Anonymous function: A line of code implements a function function.

Recursive function

Custom function: Define the function according to your needs.

(2) Classification of methods:

Common method: Method called directly with self.

Private method: uFunction name, method that can only be called in a class.

Attribute method: @property, disguising the method as an attribute makes the code look more reasonable.

Special method (double underline method): with uinit_uFor example, it is used to encapsulate the properties of an instantiated object. As long as the instantiated object is 1, it will execute uThe init method, which looks for a parent (superclass) if none of the object's subclasses exist, directly inherits the object (python 3.x) class and executes the u in the class if none of the parent (superclass) exists.init_uMethod.Class method: Operates properties and methods in a common template by calling the class name.

Static methods: Do not pass in class space, object methods, the role is to ensure code consistency, specifications, can completely separate a method outside the class, but for code consistency system 1 put in a module (py file).

Second, from the perspective of scope:

(1) Function scope: From the beginning of the function call to the end of the function execution, the space opened up during the execution will be freed automatically after returning to the caller, that is, after the function execution is completed, the value of the variable modified by assignment and so on will not be retained inside the function body, and the space opened will be freed automatically after returning to the caller.

(2) Method Scope: When a method is invoked through an instantiated object, the space opened up after the invocation will not be released, that is, the modified value of the variable in the invocation method will be kept for 1.

Finally, calls are made in different ways.

(1) Function: Called by "function name ()".

(2) Method: Call by way of "object. method name".


class Foo(object): def func(self):  pass# instantiation obj = Foo()#  Execution Mode 1: Called func Is the method obj.func() #func  Method #  Execution Mode 2 : Called func Is a function Foo.func(123) #  function 

More Python related technical articles, please visit the Python Tutorial column to learn!


Related articles: