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.
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
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.
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.
Related Topics
System-Wide Mutex in Python on Linux
Return Value of X = Os.System(..)
Splitting Out the Output of Ps Using Python
Listing Available Devices in Python-Opencv
Iterating Over Dictionaries Using 'For' Loops
Convert Columns into Rows With Pandas
Input() Error - Nameerror: Name '...' Is Not Defined
Hex/Binary String Conversion in Swift
List of Lists Changes Reflected Across Sublists Unexpectedly
How to Unnest (Explode) a Column in a Pandas Dataframe, into Multiple Rows
Get the Data Received in a Flask Request
Selenium - Wait Until Element Is Present, Visible and Interactable
What Does If _Name_ == "_Main_": Do
Application Not Picking Up .Css File (Flask/Python)
Why Do People Write #!/Usr/Bin/Env Python on the First Line of a Python Script