Correct usage of Python functions and precautions

Posted by onlyican on Mon, 03 Jan 2022 01:21:34 +0100

Brief summary:

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

First, discard the false perception: not all calls in a class are called methods

Function type

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

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 implicitly passed, 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, they can be called through class name and object name, belonging to function)

Functions implemented in a module can be used arbitrarily as long as the function of the module is imported, but those 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):
         self.name="haiyan"
     def func(self):
         print(self.name)
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 parameters 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 that the parameters are passed automatically. The method is self, and the function is active

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

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

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
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.

Difference 2: definition method:

1. The method of function definition is to use the def keyword, followed by the function name, followed by parentheses. Formal parameters can be written in parentheses or omitted

def functionName():
    """Here are the comments for 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 methods of calling:

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

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

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

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
class className:
    
    def method(self):
        print("This is a method")
 
#Call---------------------
#Instantiate object
c=className()
 
c.method()

The differences between instance methods, static methods and class methods of python classes and their application scenarios

1, Let's look at the syntax first. There are three methods in python class syntax: instance method, static method and class method.

Differences 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.

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
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))
 
    @staticmethod
    def static_method():
        print("Is a static method")
 
    @classmethod
    def class_method(cls):
        print("Is a class method")
 
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()

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
 Is a class method
----------------
Is a static method
 Is a class method

explain:

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 class instance objects.

  • 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.

Topics: Python Programming