先进的 Python 特性以更好的代码

Advanced Python Features for Better Code 先进的 Python 特性以更好的代码

参考原文

Python has many features that make development easier. Some are well known, others not so well known. In this article, I'll touch base on a few advanced tools that help coders write cleaner, more efficient code.
Python 有许多特性使得开发变得更容易。有些是众所周知的,其他则不太为人所知。在这篇文章中,我将介绍一些帮助程序员编写更干净、更高效代码的高级工具。

The features include decoratorscontext managersmetaclassesdescriptors, and slot optimization. Each serves a different purpose but improves code structure and performance.
这些功能包括装饰器、上下文管理器、元类、描述符和槽优化。每个都有不同的用途,但都改善了代码结构和性能。

Using Decorators to Modify Function Behavior

使用装饰器修改函数行为

Decorators wrap functions, adding functionality without changing the original code. A basic decorator takes a function as input, does something before or after execution, and returns a modified function.
装饰器包裹函数,在不改变原始代码的情况下添加功能。一个基本的装饰器接受一个函数作为输入,在执行前或后进行某些操作,并返回修改后的函数。

def log_function(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with arguments {args}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_function
def add(a, b):
    return a + b

add(3, 5)

The @log_function decorator adds logging without modifying the add function. When add(3, 5) runs, it prints the function call and result.
The ` @log_function ` 装饰器在不修改 ` add ` 函数的情况下添加了日志记录功能。当 ` add(3, 5) ` 运行时,它会打印函数调用和结果。

Decorators help with logging, caching, and authentication. They keep functions simple while handling extra logic separately.
装饰器有助于日志记录、缓存和身份验证。它们使函数保持简单,同时将额外的逻辑分开处理。

Managing Resources with Context Managers

管理资源上下文管理器

Certain resources require proper handling. Files, network connections, and database connections need cleanup to prevent memory leaks or unexpected behavior.
某些资源需要妥善处理。文件、网络连接和数据库连接需要清理以防止内存泄漏或意外行为。

Python's context managers simplify resource management. They ensure cleanup happens, even if an error occurs. The with statement handles this process.
Python 的上下文管理器简化了资源管理。它们确保即使发生错误也能进行清理。 with 语句处理此过程。

with open("example.txt", "w") as file:
    file.write("Hello, world!")

Once the block ends, Python automatically closes the file. No need to call file.close(). This reduces errors and keeps code cleaner.
一旦块结束,Python 会自动关闭文件。无需调用 file.close() 。这减少了错误并使代码更整洁。

Custom context managers can be created using classes.

自定义上下文管理器可以使用类来创建。

class ManagedResource:
    def __enter__(self):
        print("Resource acquired")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Resource released")

with ManagedResource():
    print("Using resource")

When the block starts, __enter__ runs. When it ends, __exit__ ensures cleanup happens.
当块开始时, __enter__ 运行。当它结束时, __exit__ 确保清理操作发生。

The contextlib module provides an easier way to define context managers.
The ` contextlib ` 模块提供了一种更简单的方式来定义上下文管理器。

from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Resource acquired")
    yield
    print("Resource released")

with managed_resource():
    print("Using resource")

Understanding Metaclasses for Custom Class Behavior
理解元类以实现自定义类的行为

Metaclasses define how classes behave. They control class creation before an object exists. Python allows modifying classes dynamically using metaclasses.
Metaclass 描述了类的行为方式。它们在创建对象之前控制类创建过程。Python 允许使用元类动态修改类。

A basic metaclass looks like this:
一个基本的元类看起来像这样:

class Meta(type):
    def __new__(cls, name, bases, class_dict):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, class_dict)

class MyClass(metaclass=Meta):
    pass

When MyClass is defined, Meta.__new__ runs before the class gets created. This prints "Creating class MyClass".
当 MyClass 被定义时, Meta.__new__ 会在类创建之前运行。这将打印出 "Creating class MyClass" 。

Metaclasses modify attributes, enforce naming conventions, or add methods automatically.
Metaclasses 修改属性,强制命名约定或自动添加方法。

For example, forcing class attributes to be uppercase:
例如强制类属性为大写:

class UpperCaseMeta(type):
    def __new__(cls, name, bases, class_dict):
        uppercase_attrs = {key.upper(): value for key, value in class_dict.items()}
        return super().__new__(cls, name, bases, uppercase_attrs)

class CustomClass(metaclass=UpperCaseMeta):
    var = "hello"

print(CustomClass.VAR)  # Prints "hello"

This ensures all attributes in CustomClass are uppercase. If var was accessed as CustomClass.var, it would fail.
这确保了 CustomClass 中的所有属性都是大写字母。如果 var 被访问为 CustomClass.var ,则会失败。

Metaclasses provide deep control over class behavior. They are useful for frameworks that create many dynamic classes.
Metaclasses 提供对类行为的深度控制。它们对于创建许多动态类的框架非常有用。

Combining for Cleaner Code
结合以获得更干净的代码

Each feature improves code structure in different ways.
每个特性以不同的方式改进了代码结构。

  • Decorators allow modifying function behavior without rewriting existing code.
    装饰器允许在不重写现有代码的情况下修改函数行为。
  • Context managers ensure resources get cleaned up, making programs more reliable.
    上下文管理器确保资源得到清理,使程序更加可靠。
  • Metaclasses customize how classes work, enabling powerful abstractions.
    元类可以定制类的工作方式,实现强大的抽象。

Together, they make Python a flexible language. Using them effectively leads to better-designed applications.
它们一起使 Python 成为一种灵活的语言。有效地使用它们可以导致设计更好的应用程序。

Descriptors Control Attribute Access
Descriptors 控制属性访问

Descriptors manage how attributes in a class are accessed, modified, and deleted. They allow fine-grained control over object attributes.
描述符管理类中属性的访问、修改和删除方式。它们允许对对象属性进行细粒度的控制。

A descriptor defines at least one of these methods:
一个描述符至少定义了以下方法中一个方法:

  • __get__ for retrieving values
    __get__ 用于获取值
  • __set__ for assigning values   __set__ 用于分配值
  • __delete__ for removing values   __delete__ 用于移除值
class Descriptor:
    def __get__(self, instance, owner):
        print("Getting value")
        return instance._value
    
    def __set__(self, instance, value):
        print("Setting value")
        instance._value = value

class MyClass:
    attr = Descriptor()

    def __init__(self, value):
        self._value = value

obj = MyClass(10)
print(obj.attr)  # Calls __get__
obj.attr = 20    # Calls __set__

Descriptors are used in frameworks like Django for model fields.
描述符在像 Django 这样的框架中用于模型字段。

Slot Optimization Reduces Memory Usage
Slot 优化减少内存使用

Python stores instance attributes in a dictionary by default. This makes attribute lookup flexible but increases memory use. The __slots__ attribute limits attributes to a predefined set, reducing memory overhead.
Python 默认情况下将实例属性存储在字典中。这使得属性查找变得灵活,但增加了内存使用。 __slots__ 属性限制属性到预定义的集合中,减少了内存开销。

class Optimized:
    __slots__ = ['x', 'y']

    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = Optimized(10, 20)
# obj.z = 30  # This would raise an error because 'z' is not in __slots__

Using __slots__ avoids storing attributes in a dictionary, improving memory efficiency.
使用 __slots__ 属性可以避免将属性存储在字典中,从而提高内存效率。

Thank you for reading this article. I hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials, please feel free to reach out. Your feedback and suggestions are always welcome!
感谢您阅读本文。希望对您有所帮助和启发。如果有任何问题,或者您愿意建议新的 Python 代码示例或主题供未来的教程使用,请随时联系我。您的反馈和建议总是受到欢迎!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值