File size: 2,237 Bytes
99a41ea |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
"""Complex class example with properties, decorators, and advanced features."""
from datetime import datetime
from typing import Optional, List
class Product:
"""Product class with advanced Python features."""
# Class variable
total_products = 0
def __init__(self, name: str, price: float, category: str):
self._name = name
self._price = price
self._category = category
self._created_at = datetime.now()
self._discount = 0.0
Product.total_products += 1
@property
def name(self) -> str:
"""Product name property."""
return self._name
@name.setter
def name(self, value: str):
if not value.strip():
raise ValueError("Product name cannot be empty")
self._name = value
@property
def price(self) -> float:
"""Product price with discount applied."""
return self._price * (1 - self._discount)
@property
def original_price(self) -> float:
"""Original price before discount."""
return self._price
@original_price.setter
def original_price(self, value: float):
if value < 0:
raise ValueError("Price cannot be negative")
self._price = value
def apply_discount(self, percentage: float):
"""Apply discount percentage."""
if 0 <= percentage <= 100:
self._discount = percentage / 100
@staticmethod
def validate_category(category: str) -> bool:
"""Validate if category is allowed."""
allowed_categories = ["electronics", "clothing", "books", "food"]
return category.lower() in allowed_categories
@classmethod
def create_book(cls, title: str, price: float):
"""Factory method to create a book product."""
return cls(title, price, "books")
@classmethod
def get_total_products(cls) -> int:
"""Get total number of products created."""
return cls.total_products
def __str__(self) -> str:
return f"{self._name} - ${self.price:.2f}"
def __repr__(self) -> str:
return f"Product(name='{self._name}', price={self._price}, category='{self._category}')"
|