Advertisement
STANAANDREY

static class py

Nov 28th, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. def static_class(cls):
  2.     """Decorator to make a class static by preventing instantiation."""
  3.     # Store the original __new__ method
  4.     original_new = cls.__new__
  5.  
  6.     # Define a new __new__ method that raises an error
  7.     def new_new(cls, *args, **kwargs):
  8.         raise TypeError(f"Cannot create instances of static class '{cls.__name__}'")
  9.  
  10.     # Replace the class's __new__ method with the new one
  11.     cls.__new__ = new_new
  12.  
  13.     return cls
  14.  
  15. @static_class
  16. class MyStaticClass:
  17.     shared_data = []
  18.  
  19.     @staticmethod
  20.     def add_data(data):
  21.         MyStaticClass.shared_data.append(data)
  22.  
  23.     @staticmethod
  24.     def get_data():
  25.         return MyStaticClass.shared_data
  26.  
  27. # Usage
  28. MyStaticClass.add_data("Hello")
  29. MyStaticClass.add_data("World")
  30. print(MyStaticClass.get_data())  # Output: ['Hello', 'World']
  31.  
  32. # Attempting to create an instance will raise an error
  33. try:
  34.     instance = MyStaticClass()
  35. except TypeError as e:
  36.     print(e)  # Output: Cannot create instances of static class 'MyStaticClass'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement