Printing All Instances of a Class

Printing all instances of a class

I see two options in this case:

Garbage collector

import gc
for obj in gc.get_objects():
if isinstance(obj, some_class):
dome_something(obj)

This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control.

Use a mixin and weakrefs

from collections import defaultdict
import weakref

class KeepRefs(object):
__refs__ = defaultdict(list)
def __init__(self):
self.__refs__[self.__class__].append(weakref.ref(self))

@classmethod
def get_instances(cls):
for inst_ref in cls.__refs__[cls]:
inst = inst_ref()
if inst is not None:
yield inst

class X(KeepRefs):
def __init__(self, name):
super(X, self).__init__()
self.name = name

x = X("x")
y = X("y")
for r in X.get_instances():
print r.name
del y
for r in X.get_instances():
print r.name

In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there's going to be a lot of cruft.

Another problem in this case is that you have to make sure to call the base class constructor. You could also override __new__, but only the __new__ method of the first base class is used on instantiation. This also works only on types that are under your control.

Edit: The method for printing all instances according to a specific format is left as an exercise, but it's basically just a variation on the for-loops.

How to print all the instances of a class in python?

you could do the following, if I got you right :

Proposal

tmp = globals().copy()
print(tmp)

for k,v in tmp.items():
if isinstance(v, A):
print(k)

You must copy the global variable dictionary, because otherwise i will be changed with the first instantiation in the for-loop:

Result:

foo
bar
star

How to get all instances of a class

You need to add self to the set.

Person.instances.add(self)

or more idiomatically

self.__class__.instances.add(self)

Also, you need to use a different name for the method that gets the instances; and it should be a classmethod, not a staticmethod.

@classmethod
def get_instances(cls):
return cls.instances

Although really you don't need a method here at all, as you can access Person.instances (the attribute) directly.

How to print instances of a class using print()?

>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

Print all properties of a Python Class

In this simple case you can use vars():

an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))

If you want to store Python objects on the disk you should look at shelve — Python object persistence.

Print statement of all the class instance method are printing at last?

please update your code as below

LinkedList ll1;
ll1.push(7);
ll1.push(5);
ll1.push(3);
ll1.push(1);
LinkedList ll2;
ll2.push(8);
ll2.push(6);
ll2.push(4);
ll2.push(2);
LinkedList ll3;
ll3.push(11);
ll3.push(10);
ll3.push(9);
ll3.push(0);
ll1.printList();
ll2.printList();
ll3.printList();


Related Topics



Leave a reply



Submit