Python 3 编程技巧:Idiomatic Python 进阶实践(二)

Python 3 编程技巧:Idiomatic Python 进阶实践(二)

learn-python3 Jupyter notebooks for teaching/learning Python 3 learn-python3 项目地址: https://gitcode.com/gh_mirrors/le/learn-python3

前言

在 Python 开发中,掌握地道的编程风格(Idiomatic Python)能显著提升代码质量和开发效率。本文将深入探讨几个 Python 中常见的编程场景,展示如何用更优雅的方式实现功能。

字符串连接的最佳实践

常见误区

初学者常使用循环和+=操作符来连接字符串:

names = ("John", "Lisa", "Terminator", "Python")
semicolon_separated = names[0]
for name in names[1:]:
    semicolon_separated += ";" + name
print(semicolon_separated)

这种方法效率较低,因为字符串在 Python 中是不可变对象,每次连接都会创建新字符串。

推荐做法

使用join()方法更高效:

semicolon_separated = ";".join(names)
print(semicolon_separated)

join()方法一次性完成所有连接操作,性能更好,代码也更简洁。

利用or操作符进行优雅赋值

传统方式

my_variable = "default value"
if a:
    my_variable = a
elif b:
    my_variable = b
elif c:
    my_variable = c
print(my_variable)

更简洁的方式

利用or操作符的短路特性:

my_variable = a or b or c or "default value"
print(my_variable)

or操作符会返回第一个为"真"的值,否则返回最后一个值。这种方式代码更简洁,逻辑更清晰。

异常处理的正确姿势

传统错误检测方式

exception_occured = False
try:
    bad_calculation = 1 / 0
except ValueError as e:
    print(f"Value error: {e}")
    exception_occured = True
except Exception as e:
    print(f"Something bad happened: {e}")
    exception_occured = True

if not exception_occured:
    print("All went well!")

使用else块改进

try:
    bad_calculation = 1 / 0
except ValueError as e:
    print(f"Value error: {e}")
except Exception as e:
    print(f"Something bad happened: {e}")
else:
    print("All went well!")

else块中的代码只会在没有异常发生时执行,逻辑更清晰。

确保资源释放的正确方式

传统方式

try:
    some_file = open("tmp.txt", "w")
    print(f"File open: {not some_file.closed}")
finally:
    some_file.close()
    print(f"File closed: {some_file.closed}")

使用上下文管理器

with open("tmp.txt", "w") as some_file:
    print(f"File open: {not some_file.closed}")
print(f"File closed: {some_file.closed}")

上下文管理器自动处理资源释放,即使发生异常也能确保资源被正确关闭。

自定义上下文管理器

from contextlib import contextmanager

@contextmanager
def my_context():
    print("Entering context")
    yield
    print("Exiting context")

with my_context():
    print("Doing work inside context")

使用contextmanager装饰器可以轻松创建自己的上下文管理器。

内置函数的妙用

手动实现最大值查找

max_value = 0
for val in secret_data:
    if val > max_value:
        max_value = val
print(max_value)

使用内置函数

max_value = max(secret_data)
print(max_value)

Python 内置函数经过优化,通常比自己实现的更高效。

优雅地忽略异常

传统方式

value = 0
try:
    value = 1 / 0
except ZeroDivisionError:
    pass
print(value)

使用suppress

from contextlib import suppress

value = 0
with suppress(ZeroDivisionError):
    value = 1 / 0
print(value)

suppress让忽略特定异常的意图更明确。

使用属性替代getter/setter

Java风格的做法

class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    def set_full_name(self, full_name):
        parts = full_name.split()
        if len(parts) != 2:
            raise ValueError("Invalid name format")
        self.first_name, self.last_name = parts

Pythonic的方式

class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    @property
    def full_name(self):
        return f"{self.first_name} {self.last_name}"

    @full_name.setter
    def full_name(self, name):
        parts = name.split()
        if len(parts) != 2:
            raise ValueError("Invalid name format")
        self.first_name, self.last_name = parts

使用@property装饰器可以让代码更符合Python风格,同时保持封装性。

结语

掌握这些Python编程技巧,能让你的代码更简洁、更高效、更易维护。记住,Python之禅告诉我们:"简单胜于复杂","明了胜于晦涩"。在编写代码时,多思考是否有更Pythonic的实现方式。

learn-python3 Jupyter notebooks for teaching/learning Python 3 learn-python3 项目地址: https://gitcode.com/gh_mirrors/le/learn-python3

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霍虹情Victorious

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值