为了账号安全,请及时绑定邮箱和手机立即绑定

如何限制可以传递给方法参数的允许值

如何限制可以传递给方法参数的允许值

肥皂起泡泡 2022-01-18 16:14:22
在 Python 3 中,我想限制传递给此方法的允许值:my_request(protocol_type, url)使用类型提示我可以写:my_request(protocol_type: str, url: str)所以协议和 url 仅限于字符串,但我如何验证protocol_type它只接受有限的一组值,例如'http'和'https'?
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超7个赞

一种方法是在方法中编写代码来验证传入的值是“http”还是“https”,如下所示:


if (protocol_type == 'http') or (protocol_type == 'https'):

  Do Something

else:

  Throw an exception

这将在运行时正常工作,但在编写代码时不会提供问题指示。


这就是为什么我更喜欢使用 Enum 以及 Pycharm 和 mypy 实现的类型提示机制的原因。


对于下面的代码示例,您将在 Pycharm 的代码检查中收到警告,请参阅随附的屏幕截图。屏幕截图显示,如果您输入的值不是枚举,您将收到“预期类型:...”警告。


代码:


"""Test of ENUM"""


from enum import Enum



class ProtocolEnum(Enum):

    """

    ENUM to hold the allowed values for protocol

    """

    HTTP: str = 'http'

    HTTPS: str = 'https'



def try_protocol_enum(protocol: ProtocolEnum) -> None:

    """

    Test of ProtocolEnum

    :rtype: None

    :param protocol: a ProtocolEnum value allows for HTTP or HTTPS only

    :return:

    """

    print(type(protocol))

    print(protocol.value)

    print(protocol.name)



try_protocol_enum(ProtocolEnum.HTTP)


try_protocol_enum('https')

输出:


<enum 'ProtocolEnum'>

http

HTTP

//img1.sycdn.imooc.com//61e676ff0001191d19160689.jpg

查看完整回答
反对 回复 2022-01-18
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

您可以检查函数中的输入是否正确:


def my_request(protocol_type: str, url: str):

    if protocol_type in ('http', 'https'):

        # Do x

    else:

        return 'Invalid Input'  # or raise an error


查看完整回答
反对 回复 2022-01-18
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

我想你可以使用装饰器,我有类似的情况,但我想验证参数类型:


def accepts(*types):

    """

    Enforce parameter types for function

    Modified from https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments

    :param types: int, (int,float), if False, None or [] will be skipped

    """

    def check_accepts(f):

        def new_f(*args, **kwds):

            for (a, t) in zip(args, types):

                if t:

                    assert isinstance(a, t), \

                           "arg %r does not match %s" % (a, t)

            return f(*args, **kwds)

        new_f.func_name = f.__name__

        return new_f

    return check_accepts

然后用作:


@accepts(Decimal)

def calculate_price(monthly_item_price):

    ...

你可以修改我的装饰器来实现你想要的。


查看完整回答
反对 回复 2022-01-18
  • 3 回答
  • 0 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号