Differences between functions and methods in Python

Brief summary:

  1. Functions that have no binding relationship with classes and instances belong to function s;
  2. Functions bound to classes and instances belong to method s.


First of all, abandon the false cognition: not all calls in a class are called methods

Function type

Functions encapsulate some independent functions and can be called directly. They can transfer some data (parameters) for processing, and then return some data (return value) or no return value. It can be defined and used directly in the module. All data passed to the function is passed explicitly.

Method (MethodType)

Similar to functions, methods encapsulate independent functions, but methods can only be called by classes or objects to represent targeted operations.
The data self and cls in the method are passed implicitly, that is, the caller of the method;
Method can manipulate data inside a class

In short, functions exist independently in python and can be used directly, and methods can only be implemented by others.
Except for static methods (independent of class and object, which can be called through class name and object name, belonging to function)

The functions implemented in the module can be used arbitrarily as long as the function of the module is imported, but the functions declared in the class must be imported into the class and then called by creating an instance or class name. It can be said that more general functions are declared directly in modules, while methods declared in classes are generally specific to a class of things

from types import MethodType,FunctionType
class Foo(object):
     def __init__(self):
     def func(self):
obj = Foo()
print(isinstance(obj.func,FunctionType))  #False
print(isinstance(obj.func,MethodType))   #True   #It shows that this is a method
print(isinstance(Foo.func,FunctionType))  #True   #This is a function.
print(isinstance(Foo.func,MethodType))  #False

yes! In the example, it is clear that the class object calls func as a method, the class calls func as a function, and passes the parameter 123 by itself!

Note that this distinction is only made in Python 3, which is all called methods in Python 2.

The biggest difference is the transfer of parameters. The method is automatic parameter self, and the function is active parameter transfer

In the future, we can judge directly by how the parameters are passed,

If you are not sure, you can see the print type

from types import FunctionType,MethodType
print(isinstance(obj.func,MethodType))    ---># True
print(isinstance(Foo.func,FunctionType))  ---># True  

Surface differences:

The difference is one location: the function is written directly in the file rather than in the class. The method is that it can only be written in the class.

The second difference is the way of definition:

 1. The method of function definition is the def keyword , followed by the function name and then parentheses. Write formal parameters in parentheses or omit them

def functionName():
    """Here are the comments of the function"""
    print("This block writes the contents of the function"

2. Method definition: first, the method is defined in the class. Other methods are roughly the same as the function definition. One thing to note here is that the method must take a default parameter (equivalent to this), except for static methods

class className(super):
    def methodName(self):
        """Here is the annotation of the method
        self amount to this;
        print("Here is the content of the method")

Three different ways of calling:

 1. Function call: function call is to write function name directly (function parameter 1, function parameter 2,...)

def functionName():
    print("This is a function")

2. Method call: the method is called through the object point method (here refers to the object method)

class className:
    def method(self):
        print("This is a method")
#Instantiate object

Differences and application scenarios of instance methods, static methods and class methods of python classes

1, First look at the syntax. There are three methods in python class syntax: instance method, static method and class method.

The difference between self and cls in ps.python

For ordinary instance methods, the first parameter needs to be self, which represents a specific instance itself.
If you use static method, you can ignore this self and use this method as an ordinary function.
For classmethod, its first parameter is cls instead of self, which represents the class itself.

# coding:utf-8
class Foo(object):
    """Class three method syntax forms"""
    def instance_method(self):
        print("Is class{}The instance method of can only be called by the instance object".format(Foo))
    def static_method():
        print("Is a static method")
    def class_method(cls):
        print("Class method")
foo = Foo()

The operation results are as follows

Is class<class '__main__.Foo'>The instance method of can only be called by the instance object
 Is a static method
 Class method
Is a static method
 Class method


Instance methods can only be called by instance objects. Static methods (Methods decorated by @ staticmethod) and class methods (Methods decorated by @ classmethod) can be called by classes or instance objects of classes.

For instance methods, the first parameter must be passed to the instance object by default. Generally, it is customary to use self.
Static method, parameters are not required.

Class method, the first parameter must be passed to the class by default. Generally, cls is used.

Tags: Python

Posted by PHPeter on Mon, 23 May 2022 22:12:54 +0300