python如何识别参数的类型?

时间:2018-08-13 06:02:06

标签: python python-3.x algorithm jupyter-notebook

我想定义一个函数,该函数返回列表的最小元素。 所以我定义了一个'minOfList'函数,如下所示:

def minOfList(a_list):
n = len(a_list)
x = a_list[0]
for i in range(n):
    if a_list[i] <= x:
        x = a_list[i]
    else:
        x = x
return x

首先,我设置一个列表并将其放入上面的函数中。

x = [1, 1, 5, 6, 9, 5, 4, 5]
minOfList(x)

然后我将x重新定义为元组并将x馈入函数。

x = (1, 1, 5, 6, 9, 5, 4, 5)
minOfList(x)

无论我将x定义为列表还是元组,该函数都能正常工作。

问题: python如何确切知道参数的哪种数据类型输入到函数中?另外,我想知道一种在定义函数时指定参数数据类型的方法吗?

2 个答案:

答案 0 :(得分:2)

或者,您可以将装饰器与注释一起使用:

def check_type(f):
    def decorated(*args, **kwargs): 
        for name, t in f.__annotations__.items(): 
            if not isinstance(kwargs[name], t):
                raise TypeError("Incorrect argument type!") 
        return f(*args, **kwargs) 
    return decorated

@check_type # Use it before any function on which you want to check argument type
def foo(bar: str):
    print(bar)

答案 1 :(得分:1)

Python不使用静态类型转换。所以简短的答案是“不,Python不知道将哪种类型的变量传递给您的函数。

但是,有一种方法可以使用isinstance()函数进行手动检查。

isinstance(your_var,type);返回True或False。

以下是与您要构建的功能有关的示例。

if isinstance(a_list, list) or isinstance(a_list, tuple):
     Your code
else:
     Return bad var type

此外,有一种方法可以使用以下语法向用户推荐该函数期望采用的变量类型:

def minOfList(a_list: list):
     return

这使用户知道他们应该传递什么类型。但是要注意,这不会强制参数类型-使用仍然可以传递任何变量。

希望这会有所帮助!