在 Python 函数中显式定义数据类型

Explicitly Define Datatype in Python Function

我想在 python 函数中定义 2 个变量,并将它们明确定义为 float。但是,当我尝试在函数参数中定义它们时,它显示语法错误。

请帮我得到想要的输出。

代码如下:

def add(float (x) , float (y)) :
    z = (x+y)
    return (print ("The required Sum is: ", z))

add (5, 8)

将函数z = float(x+y)更改为z = float(x)+ float(y)

此时我们假设我们只是将数字相加。

让我们确保始终使用浮点数。在将它们相加之前将您的参数转换为浮点数。您可以使用 float() 函数执行此操作。

好的,让我们确保无论输入什么都将其转换为浮点数

    def add(x, y):
        z = float(x)+ float(y)
        print "The required Sum is:  {}".format(z)
        return z

    add (5, 8)

但是如果 a & b 是字符串呢??需要注意这一点。

def add(x, y)
    try:
        a = float(x)  
        b = float(y)
    except ValueError:
        return None
     else:
        return True

顺便说一下,python 中不需要检查数据类型,这样就简单多了

def addSum(x,y):
    return x+y

addSum(2.2, 5.6)
7.8
addSum(float(2), float(5))
7.0
addSum(2, 5)
7
addSum("Hello ", "World!!")
'Hello World'

Python 是一种强类型的动态语言,它将类型与 而不是名称相关联。如果你想强制调用者提供特定类型的数据,唯一的方法是在你的函数中添加显式检查。

最近 type annotations 被添加到该语言中。现在您可以编写语法正确的函数规范,包括参数类型和 return 值。您的示例的注释版本为

def add(x: float, y: float) -> float:
    return x+y

不过请注意,这只是语法。 Python 解释器中的任何内容都没有。有像 mypy 这样的外部工具可以帮助你实现你的目标,它们现在正在快速成熟成为语言的一部分(尽管人们希望它们将保持严格的可选性,记住大量的类型语料库-存在的免费代码)。

注释在 pydantic, which uses them to perform data validation. This supports interesting new paradigms, exploited by (for example) the FastAPI 服务器等工具中的用途比最初预期的用途更广泛,展示了提高 Web 编码效率的巨大潜力。

不可能在Python中定义数据类型,因为它是strongly typed dynamic language但是可以 添加 类型提示 .

link: str

这是 python 中的类型提示示例。 您也可以

也看看mypy:

但是您可以检查函数中提供的实例是否是您想要的类型!

def add(x: float, y: float) -> float:
      if not isinstance(x, float):
           raise TypeError("x and y variables not of type float")

对于 y 变量也是如此!