속성을 더 많이 사용해야 하는 이유

WBOY
풀어 주다: 2024-08-21 06:14:33
원래의
760명이 탐색했습니다.

Why should you use attrs more

소개

Python의 속성 라이브러리는 클래스 생성을 단순화하고 상용구 코드를 줄이려는 개발자를 위한 획기적인 제품입니다. 이 라이브러리는 NASA에서도 신뢰받고 있습니다.
2015년 Hynek Schlawack이 만든 attrs는 특수 메서드를 자동으로 생성하고 클래스를 정의하는 깔끔하고 선언적인 방법을 제공하는 기능으로 인해 Python 개발자들 사이에서 빠르게 선호되는 도구가 되었습니다.
데이터클래스는 일종의 속성 하위 집합입니다.

속성이 유용한 이유:

  • 상용구 코드 감소
  • 코드 가독성 및 유지 관리성 향상
  • 데이터 검증 및 변환을 위한 강력한 기능 제공
  • 최적화된 구현을 통한 성능 향상

2. 속성 시작하기

설치:
attrs를 시작하려면 pip를 사용하여 설치할 수 있습니다.

pip install attrs
로그인 후 복사

기본 사용법:
다음은 attrs를 사용하여 클래스를 정의하는 방법에 대한 간단한 예입니다.

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)
로그인 후 복사

3. attrs의 핵심 기능

에이. 자동 분석법 생성:

attrs는 클래스에 대한 init, repreq 메소드를 자동으로 생성합니다.

@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
로그인 후 복사

비. 유형 및 기본값이 포함된 속성 정의:

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)
로그인 후 복사

기음. 유효성 검사기 및 변환기:

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
로그인 후 복사

4. 고급 사용법

에이. 속성 동작 사용자 정의:

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')
로그인 후 복사

비. 고정된 인스턴스 및 슬롯:

@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
로그인 후 복사

기음. 팩토리 기능 및 초기화 후 처리:

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)
로그인 후 복사

5. 모범 사례 및 일반적인 함정

모범 사례:

  • 더 나은 코드 가독성과 IDE 지원을 위해 유형 주석을 사용하세요
  • 데이터 무결성을 위한 유효성 검사기 활용
  • 불변 객체에는 고정 클래스 사용
  • 자동 메소드 생성을 활용하여 코드 중복을 줄이세요

일반적인 함정:

  • 클래스에서 @attr.s 데코레이터를 사용하는 것을 잊어버렸습니다
  • 별도의 메서드가 될 수 있는 복잡한 유효성 검사기의 남용
  • 공장 기능의 광범위한 사용이 성능에 미치는 영향을 고려하지 않음

6. 속성과 다른 라이브러리

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)
로그인 후 복사

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/ ↩

위 내용은 속성을 더 많이 사용해야 하는 이유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!