Python Basic Learning Function Method Example

  • 2021-06-28 13:17:07
  • OfStack

An example of a function approach to Python basic learning is presented.Share it for your reference, as follows:

Preface

Like other programming languages, functions (or methods) are organized and reusable snippets of code that implement single-1 or related functions.

python's functions are very flexible and can encapsulate and define another function within a single function, making programming logic more modular.

1. Function method definition for Python

Simple rules for function method definitions:

1. The function code block begins with the def keyword followed by the function identifier name and parentheses ().
2. Any incoming parameters and independent variables must be placed between parentheses.The parameters can be defined between parentheses.
3. The first line statement of a function can optionally use a document string -- to hold the function description.
4. The function content starts with a colon and is indented.
5. return [Expression] closes the function and optionally returns a value to the caller.return without an expression is equivalent to returning None.

Function demo:


def test_method():
  test_string = "test"
  return test_string

The difference between a method and a function is that a method belongs to a class and can get the properties and defined members of the calling class, accessed using self, and defined as follows:


Class A:
  self.test_string = "test"
  def test_method(self):
    return self.test_string

Note: If a method does not use a class member, it does not need to have self, i.e. method and function 1 are identical, and it becomes static method@staticmethod

2. Parameter types of functions and methods:

1. Required parameters: Required parameters must be passed into the function in the correct order.The number of calls must be the same as when declared, and the required parameters are defined within the parentheses () of the function definition.

2. Default parameters: Default parameters use the default value when calling a method or function and do not pass in the parameter. Default values are written in (within) and must follow the required parameters, such as def test_method(str, default_str = "hello")

3. Indefinite-length parameters: In addition to defining default parameters, the python function can also define variable parameters such as *args and **kwargs:

(1) There is a * sign in front of the name of the variable parameter inside the function. We can pass in 0, 1 or more parameters to the variable parameter. Inside the function, we can directly treat the variable args as an tuple.
(2) Double asterisk (**):**kwargs imports parameters as dictionaries, such as bar (1, a=2, b=3), the internal kwargs parameters are {'a': 2,'b': 3};
(3) For functions with a single asterisk * on the outside and a * sign on the outside, each parameter assigned to the function by decompression on the inside;

4. Anonymous functions: python uses lambda to create anonymous functions:

(1) lambda is only an expression, the body of function is much simpler than def;
(2) The body of lambda is an expression, not a code block.Only limited logic can be encapsulated in the lambda expression;
(3) The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace;

demo of lambda:


sum = lambda arg1, arg2: arg1 + arg2;

Call:


sum(1,2)
#  Return 3

3. Reuse and inheritance of methods:

1. Inheritance of methods:

(1) If a class inherits a base class, the constructor (uinit_u())It calls the initialization method of the base class, which adds: super().__init__() To initialize the base class;
(2) This class can call methods that exist in the base class but not in this class. This is the method that the subclass calls the parent class, which can be called directly using self;

2. The python function does not overload:

Function overloading mainly addresses two issues:

(1) Variable parameter types;

(2) Number of variable parameters.

In addition, a basic design principle is that two functions are identical only if they have different parameter types and numbers.

For case 1, the function functions are the same, but the parameter types are different. What does python do?The answer is that there is no need to process at all, because python can accept any type of parameter. If the functions are the same, then different parameter types are likely the same code in python, and there is no need to make two different functions.

For scenario 2, the function functions are the same, but the number of parameters is different. What does python do?As you know, the answer is the default parameter.Setting those missing parameters as default parameters will solve the problem.Because you assume that the functions are the same, those missing parameters will ultimately be needed.
Since both scenarios 1 and 2 have solutions, python naturally does not require function overloading

3. Method override: 1 class with self Call a method that exists in the base class but also in this class, in which case the subclass method will be called first, instead of the method that calls the parent class. If you want to call the method of the parent class, you need to use super() Parameters;

4. Additional knowledge of Python functions and methods:

Common built-in functions for Python:

(1) When the dir() function has no parameters, it returns a list of the types of variables, methods, and definitions in the current range;When you take a parameter, a list of properties and methods of the parameter is returned.If the parameter contains a method __dir__() , the method will be called;

(2) The type() function, type() returns the type of the variable with only one variable parameter, but it can return the newly created class object (dynamically created class object) with three parameters:


#  Use type() Function Definition Class 
#  Instance Method 
def __init__(self, name):
  #  Instance Properties 
  self.name = name
#  Class method 
@classmethod
def study(cls):
  pass
#  Static method 
@staticmethod
def cal_student_num():
  pass
#  Metaclasses don't do much to create them 1 New Class 
A = type(
  'A',
  (object,),
  {
    'role': 'student',
    '__init__': __init__,
    'study': study,
    'cal_student_num': cal_student_num
  })

(3) In the Python function, variables outside the function can be called by declaring a global variable (global variable name), or they can be passed into the function by passing an external variable parameter. global changes the value of the external variable.

Readers interested in Python-related content can view the site's topics: Summary of Python Function Use Techniques, Introduction and Advanced Python Object-Oriented Programming, Python Data Structure and Algorithms, Summary of Python String Operation Techniques, Summary of Python Encoding Operation Techniques, and Introduction and Advanced Classic Tutorials of Python.

I hope that the description in this paper will be helpful to everyone's Python program design.


Related articles: