在Python函数中明确定义数据类型

在Python函数中明确定义数据类型

本文介绍了在Python函数中明确定义数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to define 2 variables in python function and define them as float explicitly. However, when i tried to define them in the function parameter, it's showing syntax error.

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

Please help me get the desired output.

这是代码:

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

add (5, 8)

推荐答案

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

Python is a strongly-typed dynamic language, which associates types with values, not names. If you want to force callers to provide data of specific types the only way you can do so is by adding explicit checks inside your function.

最近刚刚添加了 类型注释 语言.现在您可以编写语法正确的函数规范,包括参数的类型和返回值.您示例的带注释版本为

Fairly recently type annotations were added to the language. and now you can write syntactically correct function specifications including the types of arguments and return values. The annotated version for your example would be

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

不过请注意,这仅是语法.Python解释器中的任何操作均不执行任何操作.有一些外部工具,例如 mypy 可以帮助您实现目标,尽管它们仍处于婴儿期.

Note, though, that this is syntax only. Nothing in the Python interpreter actions any of this. There are external tools like mypy that can help you to achieve your goal, though they are still in their infancy.

这篇关于在Python函数中明确定义数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:28