python-demo/basic_function/函数.py

48 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File : 函数.py
@Author : lichao
@Date : 2024/12/10 19:58
@Software : PyCharm
"""
# 函数默认值
def sub(x=22, y=33):
return x - y
def add(x, y):
return x + y
# 调用函数可以指定参数
print(sub(y=44, x=33))
# 最小整数池,在一定范围内为了节省内存python会将一些整数对象缓存起来当再次使用时直接引用缓存中的对象
# 对于字符串也存在类似的情况
print(id(add(3, 2))) # 4381724008
print(id(add(4, 1))) # 4381724008
def func(x, *args, **kwargs):
print(x)
print(args)
print(kwargs)
# 不定长参数 *args, **kwargs
# *args: 位置不定长参数,用来将参数打包成元组的形式
# **kwargs: 关键字不定长参数,用来将参数打包成字典的形式
func("a", "b", "c", "d", "e", "f", name="lichao", age=22)
def test_fn(a, b, c=10, *args, **kwargs):
print(a, b, c)
print(args)
print(kwargs)
test_fn(1, 2, 3, 4, name="lc")