Skip to content

Instantly share code, notes, and snippets.

@aladinoster
Created October 28, 2021 13:21
Show Gist options
  • Save aladinoster/89ec2401752bc51544622c16e4742a26 to your computer and use it in GitHub Desktop.
Save aladinoster/89ec2401752bc51544622c16e4742a26 to your computer and use it in GitHub Desktop.
Python: Conditional instantiation
"""Conditional instantiation"""
class Demo:
"""Class with conditional instantiation"""
def __new__(cls, **kwargs):
if kwargs.get("create"):
return super(Demo, cls).__new__(cls)
return None
def __init__(self, **kwargs):
if kwargs:
print(f"Instantiated with argments {kwargs}")
print(f"No instance has been created")
def __repr__(self) -> str:
return f"{self.__class__.__name__}(create=True)"
def __str__(self) -> str:
return f"{self.__class__.__name__}(create=True)"
if __name__ == "__main__":
a = Demo(create=True)
b = Demo()
print(a, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment