Created
October 28, 2021 13:21
-
-
Save aladinoster/89ec2401752bc51544622c16e4742a26 to your computer and use it in GitHub Desktop.
Python: Conditional instantiation
This file contains hidden or 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
| """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