「Python」- 语法学习笔记

问题描述

该笔记将记录:在学习 Python 过程中,我们遇到的与其他语言不同的地方,以及常见问题处理。

解决方案

pass

类似于空代码块({});

Ternary Operator(三元运算符)

a, b = 10, 20

min = a if a < b else b  # 能够嵌套

min = a < b and a or b  # [expression] and [on_true] or [on_false] 

min = (b, a) [a < b]
min = {True: a, False: b} [a < b]
min = (lambda: b, lambda: a)[a < b]())

from…import…as

import os 
import os as RealOs
from os import path as p

try…except…else

# 抛出异常
raise Exception('I know Python!')
raise NotImplementedError

# 捕获异常
try:
	return True
except ZeroDivisionError:
	print("division by zero!")
except IOError as exc:
	print('An exception flew by!')
else:
	print("result is", result)
finally:
	return False

yield

1)与 return “类似”,但是会从“停止”处继续执行(或者说,继续执行 yield 之后的代码)。
2)yield 返回的是 Generator 对象(但是,在使用时,很像可迭代的列表)。

如下示例,将演示 yield 的特性:

# 示例一:
def simpleGeneratorFun(): 
    yield 1
    yield 2
    yield 3
 
for value in simpleGeneratorFun():  
    print(value) # 将顺序打印 1 2 3

# 示例二、使用如下方法,单独调用(与「示例一」类似)
gen = simpleGeneratorFun()
print(next(gen)) # 1 
print(next(gen)) # 2
print(next(gen)) # 3

# 示例三、与前两种不同
# 每次调用 simpleGeneratorFun() 将返回新的 Generator 对象
print(next(simpleGeneratorFun())) # 1
print(next(simpleGeneratorFun())) # 1
print(next(simpleGeneratorFun())) # 1

如下示例,每次从 i += 1 继续执行:

def nextSquare(): 
	i = 1; 

	# An Infinite loop to generate squares 
	while True: 
		yield i*i				 
		i += 1 # 下一次,将从这里继续执行	 

for num in nextSquare(): 
	if num > 100: 
		break	
	print(num) 
# 将顺序输出 1 4 9 16 ...

with…as

with 提供获取和关闭资源的便捷方法。

如下两种打开文件的方法,显然后者便捷(无需明确关闭文件的代码):

# 方法一、常规的文件打开方法
file = open('file_path', 'w') 
try: 
    file.write('hello world') 
finally: 
    file.close() 
    
# 方法二、使用 with...as 方法
with open('file_path', 'w') as file: 
    file.write('hello world !') # 当执行结束后,文件会被自动关闭(由内部处理)

我们还能为自定义对象使用 with…as 语句,只需要实现 __exit__()__enter__() 方法:

class MessageWriter(object): 
    def __init__(self, file_name): 
        self.file_name = file_name 
      
    def __enter__(self): 
        self.file = open(self.file_name, 'w') 
        return self.file
  
    def __exit__(self): 
        self.file.close() 

with MessageWriter('my_file.txt') as xfile: 
    xfile.write('hello world')

还有另外的用法:

from contextlib import contextmanager

@contextmanager
def simpleGeneratorFun(): 
    yield 1
    print(5)

with simpleGeneratorFun() as n:  
    print(n)
    
# 这段代码将输出 1 5,
# 但是 1 是在 with 中输出的,而 5 则是 yield 之后,由 simpleGeneratorFun() 打印的

# with 要求操作数必须是 Context Manager,否则使用默认的 __enter__() / __exit__() 方法(也是 Context Manager)
# 对于 Generator 对象(使用 yield 关键字),控制权会返回到 Generator 中继续执行
# 其实,我们也不懂内部实现,但是它的行为是这样的。 

动态方法名

通过字符串形式指定方法名:

>>> s = 'hello'
>>> getattr(s, 'replace')('l', 'y')
'heyyo'

参考文献

with statement in Python – GeeksforGeeks
When to use yield instead of return in Python? – GeeksforGeeks
How to Use Generators and yield in Python – Real Python
28.7. contextlib — Utilities for with-statement contexts — Python 2.7.18 documentation
PEP 221 — Import As | Python.org
8. Errors and Exceptions — Python 3.9.2 documentation
Manually raising (throwing) an exception in Python – Stack Overflow
Dynamic Method Call In Python 2.7 using strings of method names – Stack Overflow
python – When to use ‘raise NotImplementedError’? – Stack Overflow
Ternary Operator in Python – GeeksforGeeks