[python] Pocet instancí objektu

David Necas (Yeti) yeti na physics.muni.cz
Středa Leden 25 19:55:47 CET 2006


=====================================================
#!/usr/bin/python
import weakref, gc

class Counted:
    reflist = []
    def __init__(self):
        Counted.reflist.append(weakref.ref(self))

    def get_count(self):
        self.reflist = [x for x in self.reflist if x() != None]
        return len(self.reflist)
    get_count = classmethod(get_count)

    def get_instances(self):
        self.reflist = [x for x in self.reflist if x() != None]
        t = [x() for x in self.reflist]
        return [x for x in t if x != None]
    get_instances = classmethod(get_instances)

a = Counted()
print Counted.get_count()
b = Counted()
print Counted.get_count()
b = Counted()
print Counted.get_count()
del b
print Counted.get_count()
print Counted.get_instances()
del a
print Counted.get_count()
print Counted.get_instances()

c = Counted()
print gc.get_referrers(c)
a = [c, Counted(), Counted()]
print gc.get_referents(a)
print gc.get_referrers(c)

print Counted.get_instances()
=====================================================

Výsledkům volání gc.get_referrers() popravdě řečeno ne vždy
rozumím, ale je to lepší než drátem do oka.

Yeti


--
That's enough.



Další informace o konferenci Python