Перейти к содержимому

Как вывести все объекты класса python

  • автор:

Print objects of a class in Python

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

Refer to the below articles to get the idea about classes and objects in Python.

Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users.

Recording all instances of a class — Python

In a programme that I am writing, I need to loop through all the instances of a class, the way I got around this was by appending every class to a list like below:

Is this the best way of doing things or is there a built in python function for this?

2 Answers 2

Your approach is ok, but I have just one mention (this is based on personal preferences): I’d iterate over a class not a list which is defined outside it. You’ll just have to define a metaclass which supports iteration.

Magic methods are always looked up on the class, so adding __iter__ to the class won’t make it iterable. However the class is an instance of its metaclass, so that is the correct place to define the __init__ method.

Please note that I also put a _ in front of your list. This is how we tell python the list we’ll create is private . I have also used if __name__ == «main»: which is good practice (it is used to execute some code only if the file was run directly, and not imported)

Second, keep this kind of thing as simple as possible. Don’t waste a lot of time and energy on something complex. This is a simple problem, keep the code as simple as possible to get the job done.

Printing all instances of a class

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?

8 Answers 8

I see two options in this case:

Garbage collector

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

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.

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.

You don’t need to import ANYTHING! Just use "self". Here’s how you do this

It’s this simple. No modules or libraries imported

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 the get_instances method.

Here a fix for the get_instances method:

or alternatively it could be done using WeakSet:

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.

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.

ConcernedOfTunbridgeWells's user avatar

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.

In my project, I faced a similar problem and found a simple solution that may also work for you in listing and printing your class instances. The solution worked smoothly in Python version 3.7; gave partial errors in Python version 3.5.

I will copy-paste the relevant code blocks from my recent project.

In Python the __str__ method in the end, determines how the object will be interpreted in its string form. I added the : in between the curly brackets, they are completely my preference for a "Pandas DataFrame" kind of reading. If you apply this small __str__ function, you will not be seeing some machine-readable object type descriptions- which makes no sense for human eyes. After adding this __str__ function you can append your objects to your list and print them as you wish.

For printing, your format in __str__ will work as default. But it is also possible to call all attributes separately:

Print an Object of a Class in Python

In this tutorial, we will look into multiple methods to print a class object in Python. Suppose we want to print a class instance using the print() function, like viewing the object’s data or values. We can do so by using the methods explained below.

Print an Object in Python Using the __repr__() Method

Please enable JavaScript

The __repr__() method returns the object’s printable representation in the form of a string. It, by default, returns the name of the object’s class and the address of the object.

When we print an object in Python using the print() function, the object’s __str__() method is called. If it is not defined then the __str__() returns the return value of the __repr__() method. That is why when we try to print an object of a user-defined class using the print() function, it returns the return value of the __repr__() method.

Therefore, we can define or override the __repr__() method to print an object’s summary or desired values.

Suppose we have a user-defined class ClassA with no __repr__() method, the below example code demonstrates the output when we try to print an object of the ClassA with no __repr__() method.

As we have not defined the __repr__() method, it has by default returned the name of the class and address of the object.

Now, let’s define the __repr__() method of the class classA , and then use the print() function. The print() and print(repr()) should return the same value.

Print an Object in Python Using the __str__() Method

The __str__() method returns the string version of the object in Python. If an object does not have a __str__() method, it returns the same value as the __repr__() method.

We have seen in the above example codes, in case the __str__() method is not defined, the print() method prints the printable representation of the object using the __repr__() method.

Now, let’s define the __str__() method of our example class ClassA and then try to print the object of the classA using the print() function. The print() function should return the output of the __str__() method.

Print an Object in Python by Adding New Class Method

Another approach can be used instead of override or define the __str__() and __repr__() methods of the class. A new print() method can be described within the class, which will print the class attributes or values of our choice.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *