Python 中数据类型的问题
Python是一种动态类型编程语言,变量的类型是在运行时分配的,无需在赋值之前定义特定类型。
a = 5
变量 a
被赋值为 5,在此之前,无需声明 a
存储整数,直接将 5 赋值给 a
。
def add(a, b):
return a+b
print(add(4, 5)) # 9
print(add(4.0, 5.0)) # 9.0
print(add('hi', 'world')) # hiworld
print(add([1,2], [3,4])) # [1, 2, 3, 4]
add
接收两个变量 a
和 b
并返回 a+b
。但 a
和 b
应该是什么数据类型呢?
Python并不在乎你传入a
和b
的参数。如果出现错误,你需要自己解决。尽管如此,类型提示可能会有所帮助。
类型提示介绍
在 Python 中,类型提示是可选的。如果不使用它们,Python 也能正常运行。然而,对于其他开发者来说,类型提示能让我们的代码更易读。
def add(a: int, b: int) -> int:
return a + b
在 a
和 b
后面加上 : int
,在函数结尾 )
后面加上 -> int
是类型提示,指示函数的参数和返回类型。
类型提示并非强制数据类型,而是为了提示而存在的,这一点需要注意。
def add(a: int, b: int) -> int:
return a + b
print(add(4, 5)) # 9
print(add(4.0, 5.0)) # 9.0
print(add('hi', 'world')) # hiworld
我们可以在 a
和 b
中传递浮点数或字符串,Python 不限制,允许代码运行。类型提示的主要目的是指导其他开发者阅读我们的代码时,明确数据类型应当为何。
类型提示的一些优势
- 其他开发人员能够快速了解函数或方法应返回的数据类型
尽管类型提示是可选的,但它是编写优秀可读代码的必备条件。
虽然仅仅使用类型提示并不能让代码变得优秀
基础类型提示
a: int = 5
# a should be an integer
变量类型提示
def avg(a:int, b:int) -> float:
return (a+b)/2
函数类型提示
复杂类型的类型提示
但如果我们有一个整数列表呢?不用担心,内置的 typing
模块提供了一些有用的类型提示功能。
from typing import List
def average(numbers: List[int]) -> float:
return sum(numbers)/len(numbers)
numbers
应是一个整数列表。
from typing import Dict
def count(d: Dict[str, int]) -> int:
# stuff
d
应该是一个字典,其中键是字符串,值是整数。
class Dog:
pass
from typing import List
def magic(dogs: List[Dog]) -> int:
# stuff
dogs
应该是一个包含自定义 dog
对象的列表。
写在最后
掌握类型提示并不困难,但它可以提高代码的可读性。在编写优秀的Python代码时,使用类型提示是至关重要的,特别是在开发大型企业应用程序并需要与其他开发人员合作时。