1. The difference between functions and methods
- The function is called directly
- What is pointed out through the object is the method
- In Python, functions and methods are reusable blocks of code that perform specific tasks. The difference between them lies in their calling methods and application scenarios.
- Functions are independent blocks of code that can be called directly by function name. Functions can accept input parameters and return a result. Functions can be defined anywhere, independent of classes or objects.
- Methods are functions in a class that are associated with specific objects. Methods must be called through an object or class. Methods can access the properties of an object and operate on them. When calling a method, the method automatically passes in the associated object as the first parameter, usually called self.
- Functions can be thought of as independent tools, while methods are more like behaviors closely associated with an object.
The following is the use of functions and methods:
# 函数示例: def calculate_sum(a, b): return a + b result = calculate_sum(3, 4) print(result) # 输出:7 # 方法示例: class Calculator: def __init__(self, value): self.value = value def add(self, number): self.value += number def get_value(self): return self.value # 创建 Calculator 对象 calculator = Calculator(10) # 调用方法 calculator.add(5) result = calculator.get_value() print(result) # 输出:15
2. Definition of function
- Use the keyword def to define a function, then specify the function name and specify the parameters in parentheses.
- In Python, a function is a reusable block of code that performs a specific task. Functions usually accept input parameters, perform corresponding operations based on the parameters, and finally return a result.
The definition of a function usually includes the following parts:
Function header : The function header includes keywords
def
, followed by the function name and a pair of parentheses()
. The function name is the name we give the function and is used to identify and call the function. Parameters can be included within the parentheses to receive input values passed when the function is called.Function body : The function body is the main part of the function and consists of a set of statements that perform a specific task. Function bodies usually consist of indented blocks that identify the scope of the function body. In the function body, it can be used to process parameters, perform operations, and finally return results.
Return value : The function can optionally return a result. This value can be passed to the caller of the function using the keyword
return
followed by the value to be returned. If no return value is explicitly specified, the function returns by defaultNone
.
Here is an example function definition:
def greet(name): """打印欢迎信息,使用传入的名字""" print("Hello, " + name + "!") # 调用函数 greet("Alice") # 输出:Hello, Alice!
In the above example,
greet
is a function that accepts one parametername
and is used to print a welcome message. Within the function body, usegreet
and pass the parameters to it."Alice"
[Note] After a function is defined, it can be called anywhere in the program to repeatedly execute the code block in it .
Define a function that outputs the result of adding two numbers
def res(a, b): print(f'a={a}') print(f'b={b}') print(f'结果={a + b}') res(1, 2)
- Python has no type restrictions on the parameters passed in.
- However, you can add a type to the parameter to prompt the type that should be passed in when calling.
res(a: int, b: int)
3. Several methods of passing parameters
- Position parameter passing
res(1, 2)
- Keyword parameter passing
res(a=1, b=2)
- Default parameters
res(a: int, b: int = 10) res(1)
Parameters with default values do not need to be passed. Parameters with default values need to be placed after parameters without default values.
- variable parameter
def res(*nums: int): val = 0 for i in nums: val += i print(val)
def res(**nums: int): val = 0 for i in nums.values(): val += i print(val)
4. Return value of function
- The return value is not limited to type, so there is no need to specify the return type
- Use return keyword
- Multiple values can be returned in the form of tuples
Write a function that accepts multiple parameters and returns the maximum value, minimum value and sum
def res(*nums: int):
val = 0
val_max = nums[0]
val_min = nums[0]
for i in nums:
val += i
val_min = i if i < val_min else val_max;
val_max = i if i > val_max else val_max;
return val, val_min, val_max
5. Comments on functions
View the description of the function in python: help()
def res(a, b):
"""
两数相加
:param a: 数字
:param b: 数字
:return: 结果
"""
return a + b
6. Others
1. Function nesting:
- Define sum function
- Complete the mean function over the sum function
2. Variable scope:
- global variables
- local variables
3. Recursive call:
Calculate the sum of 1+n
def res(target: int):
if target <= 0:
return '0'
if target == 1:
return 1
return target + res(target - 1)
Calculate Fibonacci Sequence
def res(target: int):
if target <= 0:
return '0'
if target <= 2:
return 1
return res(target - 1) + res(target - 2)
7. Lambda expression
1. Function
- Lambda expressions are a small and concise way to represent anonymous functions in Python. Unlike regular functions, Lambda expressions can create function objects without defining a function name.
The functions of lambda expressions are as follows:
Simplified function definition : The syntax of Lambda expression is concise, you can define a simple function with one line of code, and there is no need to use
def
keywords to create functions.Functions as parameters : Lambda expressions can be used as parameters of other functions, which is very convenient especially in scenarios where short function logic needs to be passed. For example, Lambda expressions are often used as parameters in functions such as sorting, mapping, and filtering.
Code readability : Lambda expressions are often used for short functional logic, which can be expressed directly in the code, avoiding the tedious process of creating separate functions. This makes the code cleaner and easier to read and understand.
Functional extension : Lambda expressions can be used with other functions to enhance the functionality of the code. By using Lambda expressions, we can quickly create and use functions where needed without having to create new function definitions for each small task.
The basic syntax of a lambda expression is:
lambda 参数: 表达式
. Among them, the parameters specify the input parameters of the function, and the expression specifies the logic and return value of the function.Here is an example that shows how to use lambda expressions to define a simple addition function:
add = lambda x, y: x + y result = add(3, 5) print(result) # 输出:8
lambda x, y: x + y
An anonymous function is defined that accepts two parametersx
andy
returns their sum. Then, we assign this Lambda expression to a variableadd
and use itadd
to call this function in subsequent code. Finally, the output is 8.
2. Example
It is equivalent to an anonymous function, which can simplify the current function and is reflected in the streaming operation and function interface in Java.
//常规
Runnable r1=new Runnable() {
@Override
public void run() {
System.out.println("你好");
}
};
//lambda表达式
Runnable r2=()->{
System.out.println("你好");
};
However, an expression in python can only exist in one line of code. Use lambda in python to simplify the function.
# 未简写
def res():
return 10
# 简写
res = lambda: 10
形式: lamdba 参数 : 执行操作/返回值
Write a function that accepts two parameters and returns the maximum value
def res(a, b):
return a if a > b else b
res = lambda a, b: a if a > b else b
Sorting dictionary data using lambda
persons = [
{"name": "张三", "age": 20},
{"name": "李四", "age": 17},
{"name": "王麻子", "age": 21}
]
persons.sort(key=lambda p: p['age'], reverse=True)
Double all values in an element map
nums = [1, 2, 3, 4, 5, 6, 7]
m = map(lambda a: a * 2, nums)
for i in m:
print(i)
Let the corresponding positions in the set be added
nums1 = [1, 2, 3, 4, 5, 6, 7]
nums2 = [2, 3, 4, 5, 6, 7, 8]
m = map(lambda a, b: a + b, nums1, nums2)
for i in m:
print(i)
Filter the collection
nums = [1, 2, 3, 4, 5, 6, 7]
f = filter(lambda a: a > 5, nums)
for i in f:
print(i)