You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何基于字符串参数动态调用ibm_boto3的client或resource函数

错误原因
  • 报错触发点为代码行method_type = getattr(ibm_boto3, object_type)()
  • ibm_boto3.client和ibm_boto3.resource方法的第一个必填参数为service_name,上述代码在获取到对应方法后,额外增加了一对空括号,无参调用了方法,直接触发参数缺失的TypeError。
  • 需求为获取方法对象后传入参数调用,仅需删除该行末尾的空括号即可。
修正后完整代码
import ibm_boto3
from ibm_botocore.config import Config

class ObjectStorage:

    def __init__(self, object_type: str, endpoint: str, api_key: str, instance_crn: str, auth_endpoint: str):

        valid_object_types = ("resource", "client")
        if object_type not in valid_object_types:
            raise ValueError("Object initialization error: Status must be one of %r." % valid_object_types)

        # 仅获取方法本身,不提前调用
        method_type = getattr(ibm_boto3, object_type)
        self._conn = method_type(
                    "s3",
                    ibm_api_key_id = api_key,
                    ibm_service_instance_id= instance_crn,
                    ibm_auth_endpoint = auth_endpoint,
                    config=Config(signature_version="oauth"),
                    endpoint_url=endpoint,
        )

    @property    
    def connect(self):
        return self._conn
使用示例
# 初始化client类型连接
cos_client = ObjectStorage(
    object_type="client",
    endpoint="你的COS_ENDPOINT",
    api_key="你的COS_API_KEY_ID",
    instance_crn="你的COS_INSTANCE_CRN",
    auth_endpoint="你的COS_AUTH_ENDPOINT"
).connect

# 初始化resource类型连接
cos_resource = ObjectStorage(
    object_type="resource",
    endpoint="你的COS_ENDPOINT",
    api_key="你的COS_API_KEY_ID",
    instance_crn="你的COS_INSTANCE_CRN",
    auth_endpoint="你的COS_AUTH_ENDPOINT"
).connect

内容的提问来源于stack exchange,提问作者Looz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:36:06