How do you implement this Python idiom in C++

Pierre Barbier de Reuille p.barbierdereuille at free.fr
Sun Jul 30 15:20:10 EDT 2006


alainpoint at yahoo.fr wrote:
> Pierre Barbier de Reuille wrote:
[...]
> 
> I thank you for your response. The equivalent of your solution is
> posted hereunder:
> class cA(object):
>         count=0
>         def __init__(self):
>                 self.__class__.count +=1
>         @classmethod
>         def getcount(cls):
>                 return cls.count
> 	def __del__(self):
> 		self.__class__.count -=1
> class cB(cA):
>         count=0
>         def __init__(self):
> 		super(cB,self).__init__()
> 		for klass in self.__class__.__bases__:
> 			klass.count +=1
> 
> a=cA() ; b=cA(); c= cA()
> d=cB() ; e=cB(); f= cB()
> a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
> g=cA()
> g.a=1
> print  '#cA=',cA.getcount()  # 7
> print '#cB=',cB.getcount() #  3
> del g
> print  '#cA=',cA.getcount()  # 6
> print '#cB=',cB.getcount() #  3
> 
> There is nothing impossible in Python ;-)
> 
> Alain
> 

Well, nothing is impossible, but it is now much much more complex ! As a
proof of that, your version does not work completely :P (try deleting d
for example).

I add a working version, but you will also notice that I have to
*explicitly* walk over all the classes of the hierarchy, testing for the
one who have a "count" attribute, hoping that this attribute is indeed
for counting the number of objects and not anything else ... so the
solution is quite fragile and very slow.

class cA(object):
        count=0
        def __init__(self):
                self.__class__.count +=1
                for klass in self.__class__.__bases__:
                        if hasattr( klass, "count" ):
                                klass.count += 1

        @classmethod
        def getcount(cls):
                return cls.count
        def __del__(self):
                self.__class__.count -=1
                for klass in self.__class__.__bases__:
                        if hasattr( klass, "count" ):
                                klass.count -= 1
class cB(cA):
        count=0

a=cA() ; b=cA(); c= cA()
d=cB() ; e=cB(); f= cB()
a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
g=cA()
g.a=1
print  '#cA=',cA.getcount()  # 7
print '#cB=',cB.getcount() #  3
del g
del d
print  '#cA=',cA.getcount()  # 5
print '#cB=',cB.getcount() #  2

Pierre



More information about the Python-list mailing list