本文汇集了一些常用的Python语法糖,供大家查询使用。
[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."""
a, b = 1, 2
*a, b = [1, 2, 3, 4]
a, *b, c = [0, 1, 2, 3, 4]
@my_decorator
def say_hello():
print("Hello!")
add = lambda x, y: x + y
**kwargs 接受任意数量的关键字参数。def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
max_value = a if a > b else b
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"
with open('file.txt') as f:
content = f.read()
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'])
from . import my_module # 相对导入
from mypackage import my_module # 绝对导入
def get_addition_result(a: int, b: int) -> int:
return a + b
async 和 await 编写异步代码。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())
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+
(element) = [1, 2, 3]
__slots__:限制实例属性,优化内存使用。class MyClass:
__slots__ = ('name', 'age')
len(), range(), min(), max(), sum() 等。len([1, 2, 3])
[1, 2, 3], (1, 2, 3), {1, 2, 3}
{'key': 'value'}
'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
__init__(), __str__(), __repr__(), __len__() 等。class MyClass:
def __init__(self, value):
self.value = value
type 作为元类:创建类的类。class MyClass(type):
pass
__all__ 定义可导入的模块成员。__all__ = ['func1', 'func2']
__path__ 属性。__import__('pkgutil').extend_path(__path__, __name__)
async with。async def async_func():
async with aiohttp.ClientSession() as session:
pass
name = 'Kimi'
f"Hello, {name}!"
with open() 管理文件。with open('file.txt', 'r') as f:
content = f.read()
warnings 模块发出警告。import warnings
warnings.warn("This is a warning message.")
getattr(), setattr(), delattr() 动态操作对象属性。getattr(obj, 'attr')
# Python's garbage collector takes care of objects
WeakRef。import weakref
weakref.ref(obj)
+, *, 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')
iter() 创建迭代器。iter([1, 2, 3])
break 和 continue 控制循环流程。for element in iterable:
if some_condition:
break # Exit the loop
else:
continue # Skip to the next iteration
==, !=, >, <, >=, <=。x == y
and, or, not。x and y or z
is, is not。x is y
in, not in。'a' in ['a', 'b', 'c']