如何使函数采用所需参数的某些组合?

问题描述 投票:0回答:1

说我有乐趣

def get_chat(first_id, first_username, second_id, second_username):
   """Returns chat between first and second"""

要识别人员,ID 或用户名就足够了。

因此,如果提供了一个参数,我想让该参数为可选参数;如果没有提供第二个参数,则该参数为必需参数。怎么办?

当然我可以将所有参数设为可选,但这似乎是错误的方式。

python python-typing
1个回答
0
投票

解决方案1:id和username是不同类型

def get_chat(first_user: str | int, second_user: str | int):
    if isinstance(first_user, int):
        first_user_id = first_user
        first_user_name = get_name_from_id(first_user)
    else:
        first_user_name = first_user
        first_user_id = get_id_from_name(first_user)
    ...

解决方案2:通用

class User:
    @classmethod
    def from_id(cls, id: int) -> typing.Self:
        ...
    
    @classmethod
    def from_username(cls, username: str) -> typing.Self:
        ...

def get_chat(first_user: User, second_user: User):
    ...

这些是我找到的最好的,感谢所有试图提供帮助的人!

© www.soinside.com 2019 - 2024. All rights reserved.