python函数快速应用

函数 f i l t e r:

函数定义:

filter(function,iterable)

函数描述:

filter(条件函数,可迭代的列表)

  参数1 是判断条件函数,

  参数2 可迭代列表

代码案例:

  声明函数案例:

    我们遍历一个列表,然后判断里面的内容,进行过滤和筛序

def focker(name):

   return name.startswith("") or name.startswith("")

if __name__ == '__main__':

   names=["张三","李四","王五","赵六","六七","王八"]
   result= filter(focker,names)
   print(list(result))

  匿名函数的使用:

if __name__ == '__main__':
   names=["张三","李四","王五","赵六","六七","王八"]
   result=filter(lambda name: name.startswith(("","")) ,names)
   print(list(result))

 

相关的 attr 函数家族

Python 还有其他的 attr 相关函数:

  • getattr(object, name)- 获取属性值
  • delattr(object, name)- 删除属性
  • hasattr(object, name)- 检查属性是否存在
  • setattr(object, name, value)- 设置属性值

from __future__ import annotations

是 Python 的一个未来特性导入,它改变了 Python 解释器处理类型注解的方式。

1. 基本含义

这行代码的意思是:"从未来的 Python 版本中导入 annotations 特性"。在 Python 3.7+ 中,这个导入让 Python 解释器以延迟评估的方式处理类型注解。

2. 具体作用

 

没有 from __future__ import annotations时:

class A: def method(self) -> B: # 错误!B 类还没有定义 pass class B: pass

 有 from __future__ import annotations时: 

from __future__ import annotations class A: def method(self) -> B: # 正常!类型注解被当作字符串处理 pass class B: pass
 
3. 工作原理

当使用 from __future__ import annotations时:

  • 类型注解不被立即评估,而是被当作字符串处理
  • 避免了循环引用问题,因为不需要在注解时实际导入类
  • 提高了代码的可读性和维护性
posted @ 2025-10-31 17:32  郎小乐  阅读(34)  评论(0)    收藏  举报