With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Very nice and useful code, but it has a big problem: list is always bigger and it is never cleaned-up, to test it just add
print(len(cls.__refs__[cls]))
at the end of theget_instances
method.Here a fix for the
get_instances
method:or alternatively it could be done using WeakSet:
Python doesn't have an equivalent to Smallktalk's #allInstances as the architecture doesn't have this type of central object table (although modern smalltalks don't really work like that either).
As the other poster says, you have to explicitly manage a collection. His suggestion of a factory method that maintains a registry is a perfectly reasonable way to do it. You may wish to do something with weak references so you don't have to explicitly keep track of object disposal.
It's not clear if you need to print all class instances at once or when they're initialized, nor if you're talking about a class you have control over vs a class in a 3rd party library.
In any case, I would solve this by writing a class factory using Python metaclass support. If you don't have control over the class, manually update the
__metaclass__
for the class or module you're tracking.See http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html for more information.
Maybe you mean something like
__str__
:A trivial example:
You'll want to create a static list on your class, and add a
weakref
to each instance so the garbage collector can clean up your instances when they're no longer needed.Same as almost all other OO languages, keep all instances of the class in a collection of some kind.
You can try this kind of thing.
Now you can do this.