公司动态

Python进阶:内置函数、函数注解、异步编程与面向对象精讲

📅 2026/8/1 6:08:54
Python进阶:内置函数、函数注解、异步编程与面向对象精讲
一、内置函数精选Python内置了丰富的函数库以下是最常用的几个1. 数值运算类print(abs(-5), abs(5)) # 5 5 print(pow(5, 3), 5**3) # 125 125 print(divmod(45, 7)) # (6, 3) 商和余数2. 逻辑判断类print(all([])) # True 空可迭代对象返回True print(all([0])) # False 存在假值 print(any([True])) # True print(any([])) # False3. 类型转换与自省print(chr(20013), ord(中)) # 中 20013 print(dir([])) # 查看列表所有属性和方法4. 动态执行s print(666) eval(s) # 执行字符串表达式二、函数注解Type Hints函数注解是Python 3.5引入的类型提示功能仅作提示不强制校验def my_add(x: int, y: int) - int: return x y print(my_add.__annotations__) # {x: class int, y: class int, return: class int} # 支持联合类型Python 3.10 def my_print(datas: list[int | str | float], obj: dict[str, str | int], n: int 100): print(datas, obj)三、异步函数async/await同步 vs 异步特性同步阻塞异步非阻塞执行方式顺序执行并发执行等待耗时操作阻塞后续代码可切换执行其他任务关键字无async/await异步示例import asyncio async def wake_up(): while True: print(醒醒啦) await asyncio.sleep(1) # 让出控制权 async def go_sleep(): while True: print(去睡觉) await asyncio.sleep(1) async def main(): # 并发执行多个协程 await asyncio.gather(wake_up(), go_sleep()) # 或批量启动 tasks [wake_up() for _ in range(10)] await asyncio.gather(*tasks) asyncio.run(main())注意异步函数返回的是协程对象需通过asyncio.run()或await启动。四、面向对象编程1. 类与实例class Person: 人类类型模板 pass p1 Person() # 创建实例 p2 Person() print(type(p1)) # class __main__.Person2. 初始化函数__init__class Person: def __init__(self, name, age): self.name name self.age age def get_name(self): return self.name def set_name(self, name): self.name name p Person(马云, 25) print(p.name) # 马云 p.set_name(马云云) print(p.get_name()) # 马云云3. 综合案例随机点与绘图import random import turtle class Point: def __init__(self, x, y): self.x x self.y y def get_x(self): return self.x def get_y(self): return self.y class Draw: def __init__(self, points): self.points points def draw_between_points(self): turtle.up() for i in range(len(self.points)): for j in range(i 1, len(self.points)): turtle.goto(self.points[i].get_x(), self.points[i].get_y()) turtle.down() turtle.goto(self.points[j].get_x(), self.points[j].get_y()) turtle.up() turtle.mainloop() # 生成3个随机点并绘制连线 points [Point(random.randint(-200, 200), random.randint(-200, 200)) for _ in range(3)] draw Draw(points) draw.draw_between_points()