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



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

请帮助我获得所需的输出。

这是代码:

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

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

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

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

但请注意,这只是语法。Python 解释器中没有任何操作。有一些外部工具,如mypy可以帮助你实现你的目标,这些工具现在正在迅速成熟,成为语言的一个既定部分(尽管人们希望它们将保持严格的可选性,记住现有的大量无类型代码语料库)。

注释在pydantic等工具中得到了比最初预期的更广泛的用途,这些工具使用它们来执行数据验证。这支持有趣的新范式,例如,被FastAPI服务器利用,展示了提高Web编码生产力的巨大潜力。

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

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

同样适用于 Y VaR!

在Python中不可能定义数据类型,因为它是强类型的动态语言,但可以添加Type-Hint。

link: str

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

也看看mypy:

  • https://github.com/python/mypy
  • http://mypy-lang.org/

将函数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'

我会使用assert isinstance

#!/usr/bin/env python3
import sys
def this_add(x: float, y: float):
assert isinstance(x, float), f"[e] {x} should be a float and it is {type(x)}"
assert isinstance(y, float), f"[e] {y} should be a float and it is {type(y)}"
z = (x+y)
return z
print(f"The required Sum is: {this_add(5.2, 8.9)}")
import unittest
class TestStringMethods(unittest.TestCase):
def test_int(self):
self.assertRaises(AssertionError, this_add, 5, 8)
def test_float(self):
self.assertEqual(14.0, this_add(5.1, 8.9) )
def test_float_and_int(self):
self.assertRaises(AssertionError, this_add, 5.1, 8)
def test_int_and_float(self):
self.assertRaises(AssertionError, this_add, 5, 8.9)
def test_tuple(self):
self.assertRaises(AssertionError, this_add, (5.1, 8.9), 0)
def test_string(self):
self.assertRaises(AssertionError, this_add, "5.1", "8.9")
unittest.main()

最新更新