[翻译]高阶Python一学就会

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## [翻译]高阶Python一学就会

papageno 2019-04-07 10:23:54 浏览402

# 高阶Python一学就会

### 装饰器

#### 作为自变量的函数

def greet(name):
print ('Hello ' + name)

def send_greetings(fun, name):
fun(name)

send_greetings(greet, 'John')

#### 闭包函数

def send_greetings(name):
def greet_message():
return ‘Hello ‘
result = greet_message() + name
print (result)
send_greetings(‘John’)

#### 从函数中返回函数

Python还允许你将一个函数作为返回值传给另一个函数。本质上来讲，我们只是将内部函数的引用传回以待后续的调用。

def classify(element):
def even_number():
print ('Element is even.')
def odd_number():
print ('Element is odd.')
if element%2 == 0:
return even_number
else:
return odd_number

classify(2)()

#### 装饰器

def my_decorator(fun):
def wrapper():
print (‘Before calling the function…’)
fun()
print (‘After calling the function…’)
return wrapper

def say_hello():
print (‘Hello!’)

say_hello = my_decorator(say_hello)

def my_decorator(fun):
def wrapper():
print (‘Before calling the function…’)
fun()
print (‘After calling the function…’)
return wrapper

@my_decorator
def say_hello():
print (‘Hello!’)

#### 上下文环境管理

__enter__ 返回要被管理的资源，而 __exit__ 完成任何可能出现的清理工作并且什么也不返回。

class File:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, type, value, trace_back):
if self.file:
self.close()

with File('example.txt') as f:
f.write('Hey hello')
f.write('See you later. Bye!!!')

__enter__with语句被调用的时候被执行。当代码块的语句执行完了的时候 __exit__ 方法会被调用。

from threading import Lock
lock = Lock()
def do_something():
lock.acquire()
raise Exception('Oops I am sorry. I have to raise it!')
lock.release()

try:
do_something()
except:
print ('Got an exception.')

from threading import Lock
lock = Lock()
def do_something():
with lock:
raise Exception('Oops I am sorry. I have to raise it!')

try:
do_something()
except:
print ('Got an exception.')

#### 连锁的异常

def chained_exceptions():
try:
raise ValueError(17)
except Exception as ex:
raise ValueError(23) from ex
if __name__ == "__main__":
chained_exceptions()

Traceback (most recent call last):
File “test.py”, line 3, in chained_exceptions
raise ValueError(23)
ValueError: 23

Traceback (most recent call last):
File “test.py”, line 3, in chained_exceptions
raise ValueError(17)
ValueError: 17
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File “test.py”, line 8, in <module> chained_exceptions()
File “test.py”, line 5, in chained_exceptions
raise ValueError(23) from ex
ValueError: 23