python 类型提示
它允许开发者在代码中显式地声明变量、函数、方法等的类型信息。这种类型声明不会影响 Python 解释器的运行,它可以帮助开发人员在编写代码时更好地理解代码中的数据类型,从而提高代码的可读性和可维护性。
基本类型
# 直接定义
age: int = 1
# 声明后定义
num: float
num = 2.0
name:str = "beike"
def printname(name: str) -> str:
return f"Hello, {name}!"
def is_even(x: int) -> bool:
return x % 2 == 0
res=printname(name)
print(res)
嵌套类型
使用标准库 typing 标记复合类型
from typing import List, Tuple, Dict, Set
my_list: List[int] = [1, 2, 3, 4]
my_tuple: Tuple[int, str, bool] = (1, "hello", True)
my_dict: Dict[str, int] = {"apple": 1, "banana": 2, "orange": 3}
my_set: Set[float] = {1.0, 2.0, 3.0}
复合类型
Union类型用于表示多种类型中的一种,Optional类型用于表示可选类型,Sequence 序列类型
from typing import Union
def func(x: Union[int, str]) -> None:
pass
from typing import Optional, Union
def func(x: Optional[Union[int, str]]) -> None:
pass
Sequence 类型的对象是可以被索引的任何东西:列表、元组、字符串、对象列表、元组列表的元组等。
def test(a: Sequence):
print(a[0])
...
Generator-Iterator
from typing import Generator
def even_numbers(n: int) -> Generator[int, None, None]:
for i in range(n):
if i % 2 == 0:
yield i
from typing import Iterator
class MyIterator:
def __init__(self):
self.current: int = 0
self.max: int = 5
def __iter__(self) -> Iterator[int]:
return self
def __next__(self) -> int:
if self.current >= self.max:
raise StopIteration
else:
self.current += 1
return self.current
Callable
from typing import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
def add(a: int, b: int) -> int:
return a + b
result = apply(add, 3, 4)
print(result) # 输出7
自定义类型
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def say_hello(person: Person) -> str:
return f"Hello, {person.name}!"
其他类型NamedTuple
from typing import NamedTuple
from collections import namedtuple
Employee = namedtuple('Employee', ["x","y"])
em = Employee(x=1, y='x')
print(em.x,em.y)
Point = NamedTuple('Point', [('x', int),
('y', str)])
p = Point(x=1, y='x')
print(p.x,p.y)
参考博客
https://www.cnblogs.com/luohenyueji/p/17387538.html
标签:__,name,python,self,提示,int,str,类型,def From: https://www.cnblogs.com/tian777/p/17390846.html