Pourquoi devriez-vous utiliser davantage les attributs

WBOY
Libérer: 2024-08-21 06:14:33
original
760 Les gens l'ont consulté

Why should you use attrs more

Introduction

La bibliothèque attrs de Python change la donne pour les développeurs qui cherchent à simplifier la création de classes et à réduire le code passe-partout. Cette bibliothèque est même approuvée par la NASA.
Créé par Hynek Schlawack en 2015, attrs est rapidement devenu un outil préféré parmi les développeurs Python pour sa capacité à générer automatiquement des méthodes spéciales et à fournir un moyen propre et déclaratif de définir des classes.
les classes de données sont une sorte de sous-ensemble d'attrs.

Pourquoi attrs est utile :

  • Réduit le code passe-partout
  • Améliore la lisibilité et la maintenabilité du code
  • Fournit des fonctionnalités puissantes pour la validation et la conversion des données
  • Améliore les performances grâce à des implémentations optimisées

2. Premiers pas avec les attributs

Installation :
Pour commencer avec attrs, vous pouvez l'installer en utilisant pip :

pip install attrs
Copier après la connexion

Utilisation de base :
Voici un exemple simple de la façon d'utiliser attrs pour définir une classe :

import attr

@attr.s
class Person:
    name = attr.ib()
    age = attr.ib()

# Creating an instance
person = Person("Alice", 30)
print(person)  # Person(name='Alice', age=30)
Copier après la connexion

3. Caractéristiques principales des attributs

un. Génération automatique de méthodes :

attrs génère automatiquement les méthodes init, repr et eq pour vos classes :

@attr.s
class Book:
    title = attr.ib()
    author = attr.ib()
    year = attr.ib()

book1 = Book("1984", "George Orwell", 1949)
book2 = Book("1984", "George Orwell", 1949)

print(book1)  # Book(title='1984', author='George Orwell', year=1949)
print(book1 == book2)  # True
Copier après la connexion

b. Définition d'attribut avec types et valeurs par défaut :

import attr
from typing import List

@attr.s
class Library:
    name = attr.ib(type=str)
    books = attr.ib(type=List[str], default=attr.Factory(list))
    capacity = attr.ib(type=int, default=1000)

library = Library("City Library")
print(library)  # Library(name='City Library', books=[], capacity=1000)
Copier après la connexion

c. Validateurs et convertisseurs :

import attr

def must_be_positive(instance, attribute, value):
    if value <= 0:
        raise ValueError("Value must be positive")

@attr.s
class Product:
    name = attr.ib()
    price = attr.ib(converter=float, validator=[attr.validators.instance_of(float), must_be_positive])

product = Product("Book", "29.99")
print(product)  # Product(name='Book', price=29.99)

try:
    Product("Invalid", -10)
except ValueError as e:
    print(e)  # Value must be positive
Copier après la connexion

4. Utilisation avancée

un. Personnalisation du comportement des attributs :

import attr

@attr.s
class User:
    username = attr.ib()
    _password = attr.ib(repr=False)  # Exclude from repr

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = hash(value)  # Simple hashing for demonstration

user = User("alice", "secret123")
print(user)  # User(username='alice')
Copier après la connexion

b. Instances et emplacements gelés :

@attr.s(frozen=True) # slots=True is the default
class Point:
    x = attr.ib()
    y = attr.ib()

point = Point(1, 2)
try:
    point.x = 3  # This will raise an AttributeError
except AttributeError as e:
    print(e)  # can't set attribute
Copier après la connexion

c. Fonctions d'usine et traitement post-init :

import attr
import uuid

@attr.s
class Order:
    id = attr.ib(factory=uuid.uuid4)
    items = attr.ib(factory=list)
    total = attr.ib(init=False)

    def __attrs_post_init__(self):
        self.total = sum(item.price for item in self.items)

@attr.s
class Item:
    name = attr.ib()
    price = attr.ib(type=float)

order = Order(items=[Item("Book", 10.99), Item("Pen", 1.99)])
print(order)  # Order(id=UUID('...'), items=[Item(name='Book', price=10.99), Item(name='Pen', price=1.99)], total=12.98)
Copier après la connexion

5. Meilleures pratiques et pièges courants

Meilleures pratiques :

  • Utilisez des annotations de type pour une meilleure lisibilité du code et une prise en charge de l'IDE
  • Exploiter les validateurs pour l'intégrité des données
  • Utiliser des classes gelées pour les objets immuables
  • Profitez de la génération automatique de méthodes pour réduire la duplication de code

Pièges courants :

  • Oublier d'utiliser le décorateur @attr.s sur la classe
  • Utilisation excessive de validateurs complexes qui pourraient être des méthodes distinctes
  • Ne pas prendre en compte l'impact sur les performances d'une utilisation intensive des fonctions d'usine

6. attrs vs autres bibliothèques

Library Features Performance Community
attrs Automatic method generation, attribute definition with types and default values, validators and converters Better performance than manual code Active community
pydantic Data validation and settings management, automatic method generation, attribute definition with types and default values, validators and converters Good performance Active community
dataclasses Built into Python 3.7+, making them more accessible Tied to the Python version Built-in Python library

attrs and dataclasses are faster than pydantic1.

Comparison with dataclasses:

  • attrs is more feature-rich and flexible
  • dataclasses are built into Python 3.7+, making them more accessible
  • attrs has better performance in most cases
  • dataclasses are tied to the Python version, while attrs as an external library can be used with any Python version.

Comparison with pydantic:

  • pydantic is focused on data validation and settings management
  • attrs is more general-purpose and integrates better with existing codebases
  • pydantic has built-in JSON serialization, while attrs requires additional libraries

When to choose attrs:

  • For complex class hierarchies with custom behaviors
  • When you need fine-grained control over attribute definitions
  • For projects that require Python 2 compatibility (though less relevant now)

7. Performance and Real-world Applications

Performance:
attrs generally offers better performance than manually written classes or other libraries due to its optimized implementations.

Real-world example:

from attr import define, Factory
from typing import List, Optional

@define
class Customer:
    id: int
    name: str
    email: str
    orders: List['Order'] = Factory(list)

@define
class Order:
    id: int
    customer_id: int
    total: float
    items: List['OrderItem'] = Factory(list)

@define
class OrderItem:
    id: int
    order_id: int
    product_id: int
    quantity: int
    price: float

@define
class Product:
    id: int
    name: str
    price: float
    description: Optional[str] = None

# Usage
customer = Customer(1, "Alice", "alice@example.com")
product = Product(1, "Book", 29.99, "A great book")
order_item = OrderItem(1, 1, 1, 2, product.price)
order = Order(1, customer.id, 59.98, [order_item])
customer.orders.append(order)

print(customer)
Copier après la connexion

8. Conclusion and Call to Action

attrs is a powerful library that simplifies Python class definitions while providing robust features for data validation and manipulation. Its ability to reduce boilerplate code, improve readability, and enhance performance makes it an invaluable tool for Python developers.

Community resources:

  • GitHub repository: https://github.com/python-attrs/attrs
  • Documentation: https://www.attrs.org/
  • PyPI page: https://pypi.org/project/attrs/

Try attrs in your next project and experience its benefits firsthand. Share your experiences with the community and contribute to its ongoing development. Happy coding!


  1. https://stefan.sofa-rockers.org/2020/05/29/attrs-dataclasses-pydantic/ ↩

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!