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
Random.Seed(): What Does It Do
How to Check If a Float Value Is a Whole Number
Python Requests Library Redirect New Url
Reading a Utf8 CSV File with Python
Pandas: Adding New Column to Dataframe Which Is a Copy of the Index Column
Efficiently Using Multiple Numpy Slices for Random Image Cropping
Download File from Web in Python 3
Elegant Ways to Support Equivalence ("Equality") in Python Classes
Importerror: No Module Named Requests
How to Use a Dll File from Python
Rotate Axis Text in Python Matplotlib
Compare Object Instances for Equality by Their Attributes
How to Check If All Elements of a List Match a Condition
How to Send a Head Http Request in Python 2
Activate a Virtualenv with a Python Script
How to Hide Console Window in Python
Embedding a Pygame Window into a Tkinter or Wxpython Frame
How to Extract the Decision Rules from Scikit-Learn Decision-Tree