Skip to content

Instantly share code, notes, and snippets.

@Paulius11
Created March 28, 2023 11:50
Show Gist options
  • Save Paulius11/f1e3f596b04a4658157d94fce2916bd3 to your computer and use it in GitHub Desktop.
Save Paulius11/f1e3f596b04a4658157d94fce2916bd3 to your computer and use it in GitHub Desktop.
python meta and __new__
# Creating sigleton
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
print("Initializing singleton...")
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # Output: True
# Let's create with metaclass dictionary key 'my_attr' with key 42
class MyMeta(type):
def __new__(cls, name, bases, attrs):
attrs["my_attr"] = 42
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=MyMeta):
pass
print(MyClass.my_attr) # Output: 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment