Python语法糖大全

发布于:2024-04-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

本文汇集了一些常用的Python语法糖,供大家查询使用。

1. 集合与序列操作

  • 列表推导式:创建列表。
    [x**2 for x in range(10)]
    
  • 字典推导式:创建字典。
    {x: x**2 for x in range(10)}
    
  • 集合推导式:创建集合。
    {x**2 for x in range(10)}
    
  • 条件列表推导:在列表推导中使用条件表达式。
    [x for x in range(10) if x % 2 == 0]
    
  • 条件字典推导:在字典推导中使用条件表达式。
    {x: x**2 for x in range(10) if x % 2 != 0}
    
  • 生成器表达式:创建迭代器。
    (x**2 for x in range(10))
    
  • 字符串字面量:单引号或双引号表示的字符串。
    s = "This is a string in double quotes."
    
  • 原始字符串:使用 r 前缀表示,忽略转义字符。
    raw_str = r"New line is represented as \n"
    
  • 多行字符串:使用三个引号表示。
    multi_line_str = """This is a multi-line
                       string with two lines."""
    

2. 赋值与解包

  • 多重赋值:一次性赋值多个变量。
    a, b = 1, 2
    
  • 扩展的可迭代解包:函数调用中解包可迭代对象。
    *a, b = [1, 2, 3, 4]
    
  • 解包赋值:从序列中解包值赋给多个变量。
    a, *b, c = [0, 1, 2, 3, 4]
    

3. 函数与Lambda

  • 装饰器:修改函数或方法的行为。
    @my_decorator
    def say_hello():
        print("Hello!")
    
  • lambda 函数:创建匿名函数。
    add = lambda x, y: x + y
    
  • 关键字参数:使用 **kwargs 接受任意数量的关键字参数。
    def print_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    

4. 控制流

  • 条件表达式:一行 if-else 逻辑。
    max_value = a if a > b else b
    
  • 异常处理:使用 try…except 语句处理错误。
    try:
        x = int(input("Please enter a number: "))
    except ValueError:
        print("That's not a valid number!")
    
  • 断言:调试目的的检查。
    assert x == y, "x does not equal y"
    

5. 上下文管理

  • with 语句:资源管理。
    with open('file.txt') as f:
        content = f.read()
    

6. 类和对象

  • 属性装饰器:创建管理对象属性的方法。
    class MyClass:
        @property
        def value(self):
            return self._value
        @value.setter
        def value(self, new_value):
            self._value = new_value
    
  • 命名元组:创建带有命名字段的元组子类。
    from collections import namedtuple
    Point = namedtuple('Point', ['x', 'y'])
    

7. 模块和包

  • 相对与绝对导入:模块的相对或绝对导入。
    from . import my_module  # 相对导入
    from mypackage import my_module  # 绝对导入
    

8. 类型提示

  • 类型注解:指定变量的预期类型。
    def get_addition_result(a: int, b: int) -> int:
        return a + b
    

9. 异步编程

  • 异步函数:使用 asyncawait 编写异步代码。
import asyncio

# 定义一个异步函数,模拟异步数据获取
async def fetch_data():
    # 模拟异步操作,例如网络请求
    await asyncio.sleep(1)
    return {"data": 1}

# 定义主协程,调用异步函数并打印结果
async def main():
    data = await fetch_data()
    print(data)

# 使用 asyncio.run() 运行主协程,适用于 Python 3.7 及以上版本
asyncio.run(main())

10. 其他

  • 表达式末尾的逗号:在表达式末尾使用逗号,方便添加或删除元素。
    my_list = [1, 2, 3, ]
    
  • 星号参数和双星号参数:在函数定义中收集任意数量的参数。
    def func(*args, **kwargs):
        print(args, kwargs)
    
  • 异常的 as 用法:捕获异常的实例。
    try:
        1 / 0
    except ZeroDivisionError as e:
        print(f"Caught an exception: {e}")
    
  • 海象运算符:在表达式中进行赋值(Python 3.8+)。
    # Python 3.8+
    (element) = [1, 2, 3]
    
  • 使用 __slots__:限制实例属性,优化内存使用。
    class MyClass:
        __slots__ = ('name', 'age')
    

11. 内建函数和操作

  • 内建函数:如 len(), range(), min(), max(), sum() 等。
    len([1, 2, 3])
    
  • 序列字面量:创建列表、元组、集合。
    [1, 2, 3], (1, 2, 3), {1, 2, 3}
    
  • 字典字面量:创建字典。
    {'key': 'value'}
    
  • 条件表达式:简化 if-else 语句。
    'active' if is_active else 'inactive'
    
  • 迭代器解包:在函数调用中解包迭代器。
    [a, b] = iter_range
    
  • 参数解包:在函数调用中解包序列或字典。
    def func(a, b, c): pass
    func(*args, **kwargs)
    
  • 链式比较:简化多重比较。
    a < b < c
    
  • 内建序列方法:如 .append(), .extend(), .insert(), .remove(), .pop() 等。
    my_list.append('new item')
    
  • 内建字典方法:如 .get(), .keys(), .values(), .items() 等。
    my_dict.get('key')
    
  • 内建集合操作:如 .union(), .difference(), .intersection(), .symmetric_difference() 等。
    set_a.union(set_b)
    
  • 内建迭代器:如 enumerate(), zip(), filter(), map() 等。
    enumerate(['a', 'b', 'c'])
    
  • 内建类型转换:如 int(), float(), str(), bytes() 等。
    int('123')
    
  • 内建逻辑操作:如 and, or, not
    x and y or z
    
  • 内建身份操作:如 is, is not
    x is not None
    
  • 内建比较:比较运算符 ==, !=, >, <, >=, <=
    x > y
    
  • 内建数学运算:如 +, -, *, /, //, **
    x + y
    

12. 特殊方法

  • 特殊方法:如 __init__(), __str__(), __repr__(), __len__() 等。
    class MyClass:
        def __init__(self, value):
            self.value = value
    

13. 元类和类创建

  • 使用 type 作为元类:创建类的类。
    class MyClass(type):
        pass
    

14. 模块属性和包

  • 模块属性:如 __all__ 定义可导入的模块成员。
    __all__ = ['func1', 'func2']
    
  • 命名空间包:使用 __path__ 属性。
    __import__('pkgutil').extend_path(__path__, __name__)
    

15. 协程与异步IO

  • 异步上下文管理器:使用 async with
    async def async_func():
        async with aiohttp.ClientSession() as session:
            pass
    

16. 格式化字符串字面量

  • f-strings:格式化字符串。
    name = 'Kimi'
    f"Hello, {name}!"
    

17. 文件操作

  • 文件上下文管理器:使用 with open() 管理文件。
    with open('file.txt', 'r') as f:
        content = f.read()
    

18. 警告与反射

  • 警告机制:使用 warnings 模块发出警告。
    import warnings
    warnings.warn("This is a warning message.")
    
  • 反射:使用 getattr(), setattr(), delattr() 动态操作对象属性。
    getattr(obj, 'attr')
    

19. 垃圾回收与循环引用

  • 垃圾回收机制:自动管理内存。
    # Python's garbage collector takes care of objects
    
  • 循环引用处理:自动解除循环引用的 WeakRef
    import weakref
    weakref.ref(obj)
    

20. 内建数据类型操作

  • 序列操作:如 +, *, in, not in
    [1, 2] + [3, 4]
    
  • 字典操作:如 dict.pop(), dict.setdefault()
    my_dict.pop('key', 'default')
    
  • 集合操作:如 set.add(), set.remove()
    my_set.add('new item')
    

21. 内建迭代与循环控制

  • 迭代器:使用 iter() 创建迭代器。
    iter([1, 2, 3])
    
  • 循环控制:使用 breakcontinue 控制循环流程。
    for element in iterable:
        if some_condition:
            break  # Exit the loop
        else:
            continue  # Skip to the next iteration
    

22. 内建比较与逻辑运算

  • 比较运算符==, !=, >, <, >=, <=
    x == y
    
  • 逻辑运算符and, or, not
    x and y or z
    

23. 内建身份与成员运算

  • 身份运算符is, is not
    x is y
    
  • 成员运算符in, not in
    'a' in ['a', 'b', 'c']