Created
April 20, 2012 12:03
-
-
Save isubuz/2428089 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() |
Author
Author
Updated to call type.call().
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs improvement (line 14)