Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def static_class(cls):
- """Decorator to make a class static by preventing instantiation."""
- # Store the original __new__ method
- original_new = cls.__new__
- # Define a new __new__ method that raises an error
- def new_new(cls, *args, **kwargs):
- raise TypeError(f"Cannot create instances of static class '{cls.__name__}'")
- # Replace the class's __new__ method with the new one
- cls.__new__ = new_new
- return cls
- @static_class
- class MyStaticClass:
- shared_data = []
- @staticmethod
- def add_data(data):
- MyStaticClass.shared_data.append(data)
- @staticmethod
- def get_data():
- return MyStaticClass.shared_data
- # Usage
- MyStaticClass.add_data("Hello")
- MyStaticClass.add_data("World")
- print(MyStaticClass.get_data()) # Output: ['Hello', 'World']
- # Attempting to create an instance will raise an error
- try:
- instance = MyStaticClass()
- except TypeError as e:
- print(e) # Output: Cannot create instances of static class 'MyStaticClass'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement