**kwargs,None,传参

函数

def greet(name):
    """返回问候语(文档字符串)"""
    return f"Hello, {name}!"

传参类型
| 参数类型 | 示例 | 说明 |
| ----------------- ----| ------------------ | ------------------ |
| 位置参数 | func(a, b) | 按顺序传参 |
| 关键字参数 | func(a=1, b=2) | 指定参数名 |
| 默认参数 | def func(a=1) | 参数默认值 |
| 可变参数(args) | def func(args) | 接收任意数量位置参数(元组) |
| 关键字可变参数(kwargs) | def func(kwargs) | 接收任意数量关键字参数(字典) |

kwargs】
关键字可变参数(
kwargs) 允许函数接收任意数量的 关键字参数(key-value 对),并将它们存储为一个 字典(dict)。

def show_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

show_info(name="Alice", age=25, city="New York")
def connect_db(**kwargs):
    default_config = {"host": "localhost", "port": 3306}
    final_config = {**default_config, **kwargs}  # 合并字典
    print(f"连接到数据库: {final_config}")

connect_db(port=5432, user="admin", password="123456")

**kwargs,位置最后

def func(a, b=2, *args, **kwargs):
    print(f"a={a}, b={b}, args={args}, kwargs={kwargs}")

func(1, 3, 4, 5, x=6, y=7)

输出结果:a=1, b=3, args=(4, 5), kwargs={'x': 6, 'y': 7}

【None】
用于表示 空值 或 未定义的变量

def greet(name=None):
    if name is None:
        print("Hello, Guest!")
    else:
        print(f"Hello, {name}!")

greet()          # 输出: Hello, Guest!
greet("Alice")   # 输出: Hello, Alice!
def connect_db(host, port=None):
    if port is None:
        port = 3306  # 默认端口
    print(f"连接到 {host}:{port}")

connect_db("localhost")          # 输出: 连接到 localhost:3306
connect_db("example.com", 5432) # 输出: 连接到 example.com:5432
x = None
if x is None:  # 正确方式
    print("x 是 None")

if x == None:  # 不推荐(可能被重载 __eq__ 影响)
    print("这种方式也能工作,但不推荐")
posted @ 2025-06-04 20:58  呆呆酱  阅读(26)  评论(0)    收藏  举报