navred61's picture
copied from private space
99a41ea
raw
history blame
2.24 kB
"""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}')"