Python 如何通过关键字调用函数并传参,附参考代码

参考一个微信开发的代码,通过关键字关联到函数去执行,我运行后 刚刚测试居然好使,发出来大家讨论下有啥优化的地方! 代码如下

# -*- coding: utf-8 -*-
# python3.6
# 小程序获取二维码示例
from bottle import response,route,run,template,request,redirect
from bottle import get, post# or route
import urllib
import urllib.parse as up
import urllib.request as ur
import xml.etree.ElementTree as ET

import json,time,os,re import hashlib import requests

from wx_api import *

from wx_config import *

from wechatpy import parse_message msg_type_resp = {}

class message(): type=“text” content=“取消” def set_msg_type(msg_type): “”" 储存微信消息类型所对应函数(方法)的装饰器 “”" def decorator(func): msg_type_resp[msg_type] = func return func return decorator

@set_msg_type(‘text’) def text_resp(): “”“文本类型回复”"" # 默认回复微信消息 response = ‘success’ # 替换全角空格为半角空格 message.content = message.content.replace(u’ ‘, ’ ‘) # 清除行首空格 message.content = message.content.lstrip() # 指令列表 commands = { u’取消’: cancel_command, u’^?|^?’: all_command } # 匹配指令 command_match = False for key_word in commands: if re.match(key_word, message.content): # 指令匹配后,设置默认状态 response = commandskey_word command_match = True break if not command_match: # 匹配状态 state = get_user_state(openid) # 关键词、状态都不匹配,缺省回复 if state == ‘default’ or not state: response = command_not_found() else: response = state_commandsstate return response def cancel_command(): print(‘cancel_command’) def all_command(): print(‘all_command’) def index(): try: get_resp_func = msg_type_resp[message.type] response = get_resp_func() except KeyError: # 默认回复微信消息 response = ‘success’ # 储存微信消息类型所对应函数(方法)的字典 print(index())


Python 如何通过关键字调用函数并传参,附参考代码

1 回复

# 通过关键字调用函数并传参的几种方法

# 1. 直接使用关键字参数调用
def process_data(name, age, city="Beijing"):
    return f"{name}, {age}岁, 来自{city}"

# 直接传递关键字参数
result = process_data(name="张三", age=25, city="上海")
print(result)  # 输出: 张三, 25岁, 来自上海

# 2. 使用字典解包传递关键字参数
def calculate(x, y, operation="add"):
    if operation == "add":
        return x + y
    elif operation == "subtract":
        return x - y
    elif operation == "multiply":
        return x * y
    else:
        return x / y

# 准备参数字典
params = {"x": 10, "y": 5, "operation": "multiply"}

# 使用 ** 解包字典作为关键字参数
result = calculate(**params)
print(f"计算结果: {result}")  # 输出: 计算结果: 50

# 3. 动态调用函数并传递关键字参数
def send_email(to, subject, body, cc=None, bcc=None):
    email_info = {
        "收件人": to,
        "主题": subject,
        "正文": body
    }
    if cc:
        email_info["抄送"] = cc
    if bcc:
        email_info["密送"] = bcc
    return email_info

# 动态构建参数字典
email_params = {
    "to": "user@example.com",
    "subject": "测试邮件",
    "body": "这是一封测试邮件",
    "cc": "manager@example.com"
}

# 动态调用
email_result = send_email(**email_params)
print(f"邮件信息: {email_result}")

# 4. 使用functools.partial预设关键字参数
from functools import partial

def create_report(title, author, date, format="pdf", confidential=False):
    return {
        "title": title,
        "author": author,
        "date": date,
        "format": format,
        "confidential": confidential
    }

# 预设部分关键字参数
create_pdf_report = partial(create_report, format="pdf", confidential=True)
create_word_report = partial(create_report, format="docx", confidential=False)

# 调用预设函数
report1 = create_pdf_report(title="年度报告", author="张三", date="2024-01-15")
report2 = create_word_report(title="项目总结", author="李四", date="2024-01-16")

print(f"PDF报告: {report1}")
print(f"Word报告: {report2}")

# 5. 使用**kwargs接收任意关键字参数
def process_order(order_id, **kwargs):
    order_details = {
        "order_id": order_id,
        "status": "processing"
    }
    order_details.update(kwargs)
    return order_details

# 传递任意关键字参数
order = process_order(
    "ORD12345",
    customer="张三",
    amount=299.99,
    items=["商品A", "商品B"],
    priority=True
)
print(f"订单详情: {order}")

# 运行测试
if __name__ == "__main__":
    # 测试所有示例
    print("=" * 50)
    print("关键字参数调用示例运行结果:")
    print("=" * 50)

核心要点:

  • 直接使用参数名=值的形式传递关键字参数
  • 使用**字典解包传递多个关键字参数
  • functools.partial可以预设部分参数
  • **kwargs可以接收任意数量的关键字参数

一句话建议:根据参数是否已知选择直接传递或字典解包方式。

回到顶部