SoFunction
Updated on 2024-11-14

Summary of the difference between python functions and methods

(1) Classification of functions:

Built-in functions: some functions embedded in python.

Anonymous function: one line of code to realize a function function.

recursive function

Custom Functions: Define functions according to your needs.

(2) Classification of methods:

Ordinary methods: methods that are called directly with self.

Private method: __ function name, a method that can only be called in the class.

Property methods: @property, which disguises methods as properties to make the code look more sensible.

Special methods (double underscore methods): __init__, for example, is used to encapsulate the attributes of the instantiated object, as long as the object is instantiated it will definitely execute the __init method, if the object is not available in the subclass then it will look for the parent (superclass), if the parent (superclass) is not available as well then it will directly inherit from the object (python ) class, and execute the __init__ method in the class. class methods: through the call of the class name. Class Methods: The class name is invoked to manipulate the properties and methods in the public template.

Static methods: do not have to pass the class space, the object of the method, the role is to ensure the consistency of the code, standardization, can be completely independent of the class outside of a method, but in order to achieve consistency of the code uniformly placed in a module (py file).

Second, analyze it from a scope perspective:

(1) Function scope: from the beginning of the function call to the completion of the function execution, return to the caller, in the process of execution of the open space will be automatically released, that is to say, after the completion of the function execution, the function of the body of the internal modification of the variable through the assignment of the value of the value will not be retained, it will be returned to the caller with the return to the open space will be automatically released.

(2) Method scoping: method calls are made through instantiated objects, and the space opened after the call is not released, which means that the modified values of the variables in the called method will be retained.

Finally, the invocations are different.

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

(2) Methods: Called by "Object. Method name" way to call.

class Foo(object): def func(self):  pass#instantiatedobj = Foo()# Implementation modality I:invokedfuncIt's the method.() #func methodologies# Implementation modality II:invokedfuncis a function (math.)(123) # function (math.)

For more Python-related technical articles, visit the Python Tutorials section to learn!