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

Python中如何简洁实现Authenticator构造器二选一参数传入?

Python 二选一参数类构造实现方案

核心实现逻辑

给两个参数设置默认值None,在构造方法内校验参数合法性——确保必须且只能传入其中一个,同时保留原参数定义。

代码示例

class Authenticator:
    def __init__(self, api_key: str | None = None, user_pass: tuple[str, str] | None = None):
        # 校验参数规则:二选一,不能同时传或都不传
        if (api_key is None and user_pass is None) or (api_key is not None and user_pass is not None):
            raise ValueError("必须传入api_key或user_pass中的一个,不可同时传入或都不传入")
        
        self.api_key = api_key
        self.user_pass = user_pass

使用示例

# 合法:仅传入api_key
auth_via_key = Authenticator(api_key="your_api_key_here")

# 合法:仅传入user_pass
auth_via_pass = Authenticator(user_pass=("username", "password"))

# 非法:同时传入两个参数,会抛出ValueError
# auth_invalid_1 = Authenticator(api_key="key", user_pass=("user", "pass"))

# 非法:都不传入参数,会抛出ValueError
# auth_invalid_2 = Authenticator()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:30:52