Skip to content

Instantly share code, notes, and snippets.

@isubuz
Created April 20, 2012 12:03
Show Gist options
  • Select an option

  • Save isubuz/2428089 to your computer and use it in GitHub Desktop.

Select an option

Save isubuz/2428089 to your computer and use it in GitHub Desktop.
Counting instances per class using metaclass
"""
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()
@isubuz
Copy link
Author

isubuz commented Apr 20, 2012

Needs improvement (line 14)

@isubuz
Copy link
Author

isubuz commented Apr 20, 2012

Updated to call type.call().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment