Created
March 28, 2023 11:50
-
-
Save Paulius11/f1e3f596b04a4658157d94fce2916bd3 to your computer and use it in GitHub Desktop.
python meta and __new__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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