网站上文章字体部分复制怎么做,2345网址大全设主页,做网站的好项目,最新裁员公司名单python 33个高级用法技巧
列表推导式 简化了基于现有列表创建新列表的过程。
squares [x**2 for x in range(10)]
print(squares)[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]字典推导式 用简洁的方式创建字典。
square_dict {x: x**2 for x in range(10)}
print(square_dict){0…
python 33个高级用法技巧
列表推导式 简化了基于现有列表创建新列表的过程。
squares =[x**2for x inrange(10)]print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
字典推导式 用简洁的方式创建字典。
square_dict ={x: x**2for x inrange(10)}print(square_dict)
defmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapper@my_decoratordefsay_hello():print("Hello!")say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
类装饰器 使用类来实现装饰器。
classDecorator:def__init__(self, func):self.func = funcdef__call__(self):print("Something is happening before the function is called.")self.func()print("Something is happening after the function is called.")@Decoratordefsay_hello():print("Hello!")say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
生成器函数 创建迭代器,逐个返回值。
defmy_generator():for i inrange(3):yield ifor value in my_generator():print(value)
0
1
2
异步生成器 异步生成值。
import asyncio
import nest_asyncionest_asyncio.apply()asyncdefmy_gen():for i inrange(3):yield iawait asyncio.sleep(1)asyncdefmain():asyncfor value in my_gen():print(value)asyncio.run(main())
0
1
2
元类 控制类的创建行为。
classMeta(type):def__new__(cls, name, bases, dct):print(f'Creating class {name}')returnsuper().__new__(cls, name, bases, dct)classMyClass(metaclass=Meta):pass
Creating class MyClass
数据类 简化类的定义。
from dataclasses import dataclass@dataclassclassPerson:name:strage:intp = Person(name='Alice', age=30)print(p)
Person(name='Alice', age=30)
NamedTuple 创建不可变的命名元组。
from collections import namedtuplePoint = namedtuple('Point',['x','y'])
p = Point(1,2)print(p)