【问题标题】:How to define a function that only accepts string如何定义一个只接受字符串的函数
【发布时间】:2020-06-30 15:25:48
【问题描述】:

你好,我是 python 的新手,我想知道我是否可以创建一个只接受某些类型的值的函数,在这种情况下是字符串,否则会出错

 parameter that needs to be string
            |
            v
def isfloat(a):
    if a.count('.') > 1:
        return False
    for c in a:
        if c.isnumeric() or c == '.':
            v = True
        else:
            return False
    return v

【问题讨论】:

  • 如果想知道a是不是str,可以使用isinstance(a,str)。
  • if not isinstance(argument, str): raise ValueError('argument has to be a string')
  • 总是添加你的代码,而不是图像,这样我们就可以测试它而不是再次重写它。

标签: python python-3.x function


【解决方案1】:

在 Python 3.5+ 中,您可以使用 typing 来注释您的函数:

def isfloat(a: str):
    # More code here...

但是类型注解实际上并不检查类型!

因此,最好使用assert 语句添加健壮的类型检查:

def isfloat(a: str):
    assert isinstance(a, str), 'Strings only!'
    # More code here...

使用assert,如果a 不是字符串,您的函数将引发AssertationError。

【讨论】:

    【解决方案2】:

    您可以将代码包含在 if 语句中,如下所示。

    def enumerico(a):
        if (isinstance(a, str)):
            <your code>
        else:
            <throw exception or exit function>
    

    【讨论】:

    • 请注意,如果a 是str 子类的一个实例,则type(a) is str 返回False。 isinstance(a, str) 更好。
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2021-09-10
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    相关资源
    最近更新 更多