Created
April 19, 2020 11:18
-
-
Save Krakenus/f5941045566d439e6f0639fb0376faeb to your computer and use it in GitHub Desktop.
Python metaclasses
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
class AutoIncrementIDMeta(type): | |
__counter = {} | |
def __call__(cls, *args, **kwargs): | |
if cls.__name__ not in cls.__counter: | |
cls.__counter[cls.__name__] = 0 | |
cls.__counter[cls.__name__] += 1 | |
instance = super().__call__(*args, **kwargs) | |
instance.id = cls.__counter[cls.__name__] | |
return instance | |
class AutoObjectSetMeta(type): | |
def __new__(mcs, *args, **kwargs): | |
cls = super().__new__(mcs, *args, **kwargs) | |
cls.instances = set() | |
return cls | |
def __call__(cls, *args, **kwargs): | |
instance = super().__call__(*args, **kwargs) | |
cls.instances.add(instance) | |
return instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment