-
-
Save datavudeja/e8b927bdb0cac762c8889c8f3faff8af to your computer and use it in GitHub Desktop.
Counting instances per class using metaclass
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
| """ | |
| A mechanism to keep track of no. of class instances created. | |
| """ | |
| from __future__ import print_function | |
| class CountInstances(type): | |
| def __new__(meta, classname, supers, classdict): | |
| classdict['numInstances'] = 0 | |
| return type.__new__(meta, classname, supers, classdict) | |
| def __call__(klass, *args, **kwargs): | |
| klass.numInstances += 1 | |
| return type.__call__(klass, *args, **kwargs) | |
| def printNumInstances(klass): | |
| print('No. of instances are:', klass.numInstances) | |
| class A: | |
| __metaclass__ = CountInstances | |
| def __init__(self): | |
| pass | |
| def ameth(self): | |
| print('A') | |
| class B: | |
| __metaclass__ = CountInstances | |
| def __init__(self): | |
| pass | |
| def bmeth(self): | |
| print('B') | |
| if __name__ == '__main__': | |
| a1, a2 = A(), A() | |
| b1, b2, b3 = B(), B(), B() | |
| a1.ameth() | |
| b1.bmeth() | |
| A.printNumInstances() | |
| B.printNumInstances() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment