python—为什么我的函数参数不是给定类型时的检查不起作用?

j91ykkif  于 2021-09-08  发布在  Java
关注(0)|答案(4)|浏览(398)

我有一个非常简单的函数,它接受一个字符串作为输入,我尝试对函数进行检查,这样如果函数参数不是字符串,它将抛出一个错误,否则返回字符串。
现在的问题是,当我通过 int ,我希望函数显示一个错误,但它只是输出一个 int . 我这里出了什么错?

def speak(*languages):

    """Function takes a set of langs as input  and returns a list of languages"""

    try:
        if  type(languages) ==  str:
            languages = list(languages)
    except TypeError as error:
        print(error, ' You need to pass in the right datatype')
    else:
        return languages

我也试过这个。

def speak(*languages):

    """Function takes a set of langs as input  and returns a list of languages"""

    try:
        if  isinstance(languages, str):
            languages = list(languages)
    except TypeError as error:
        print(error, ' You need to pass in the right datatype')
    else:
        return languages

我通过以下方式调用speak函数。
讲(‘英语’)-预期输出应为 english 讲(‘英语’、‘法语’)-预期输出应为 englishfrench speak(34)-我希望函数抛出一个错误

ijnw1ujt

ijnw1ujt1#

在提供示例调用之后,您似乎希望检查字符串类型的所有参数,而不是一个参数。正确的?
你可以用 any 对于该值,如果列表/生成器值中的任何一个为真,则该值为真。在生成器理解中,您可以执行以下操作: isinstance 所有(位置)参数

def speak(*languages):
    """Function takes a set of langs as input  and returns a list of languages"""

    if any(not isinstance(lang, str) for lang in languages):
        raise TypeError('You need to pass in the right datatype')

    return list(languages)
>>> speak('english')
>>> speak('english', 'french')
>>> speak(34)
Traceback (most recent call last):
  File "<string>", line 14, in <module>
  File "<string>", line 5, in speak
TypeError: You need to pass in the right datatype
vawmfj5a

vawmfj5a2#

我认为这里不需要尝试。或许可以尝试以下方式(按照您的推理):

def speak(*languages):

    """Function takes a set of langs as input  and returns a list of languages"""
    for lang in list(languages):
        if not isinstance(lang, str):
            print(' You need to pass in the right datatype')
            return
    else:
        languages = list(languages)
        return languages

print(speak('english')) # english
print(speak('english', 'french')) # english and french
print(speak(34)) # error
mum43rcc

mum43rcc3#

也不 type(languages) == str 也没有 isinstance(languages, str) 将抛出一个 TypeError ,那么你的 except 永远不会被击中。你只需要一个 else 在你 if :

def speak(*languages):
    """Function takes a set of langs as input and returns a list of languages"""

    if isinstance(languages, str):
        return list(languages)
    else:
        raise TypeError('You need to pass in the right datatype')

注:我认为你不想要 list(languages) 以上- list("a str") 给予 ['a', ' ', 's', 't', 'r'] . 但我留下它是因为它与问题无关。

gmol1639

gmol16394#

您实际上并没有在这里抛出错误,为此,您需要使用 raise :

def speak(*languages):

    """Function takes a set of langs as input  and returns a list of languages"""

    if  isinstance(languages, str):
        languages = list(languages)

    else:
        raise TypeError('You need to pass in the right datatype')

    return languages

相关问题