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

📅  最后修改于: 2022-05-13 01:55:19.080000             🧑  作者: Mango

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

与其他语言Java、C++ 等不同, Python是一种强类型的动态语言,我们不必指定函数返回值和函数参数的数据类型。它将类型与值而不是名称相关联。指定特定类型数据的唯一方法是在调用函数时提供显式数据类型。

示例 1:我们有一个添加 2 个元素的函数。

Python3
# function definition
def add(num1, num2):
    print("Datatype of num1 is ", type(num1))
    print("Datatype of num2 is ", type(num2))
    return num1 + num2
  
# calling the function without
# explicitly declaring the datatypes
print(add(2, 3))
  
# calling the function by explicitly
# defining the datatype as float
print(add(float(2), float(3)))


Python3
# function definition
def concatenate(num1, num2):
    print("Datatype of num1 is ", type(num1))
    print("Datatype of num2 is ", type(num2))
    return num1 + num2
  
# calling the function without
# explicitly declaring the datatypes
print(concatenate(111, 100))
  
# calling the function by explicitly
# defining the datatype as float
print(concatenate(str(111), str(100)))


输出:

Datatype of num1 is  
Datatype of num2 is  
5
Datatype of num1 is  
Datatype of num2 is  
5.0

示例 2:我们有一个用于字符串连接的函数

Python3

# function definition
def concatenate(num1, num2):
    print("Datatype of num1 is ", type(num1))
    print("Datatype of num2 is ", type(num2))
    return num1 + num2
  
# calling the function without
# explicitly declaring the datatypes
print(concatenate(111, 100))
  
# calling the function by explicitly
# defining the datatype as float
print(concatenate(str(111), str(100)))

输出:

Datatype of num1 is  
Datatype of num2 is  
211
Datatype of num1 is  
Datatype of num2 is  
111100