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.
Printing a list of objects of user defined class
I want to print a list of objects of this class, like this:
but it shows me output like this:
Actually, I wanted to print the value of Vertex.label for each object. Is there any way to do it?
3 Answers 3
If you just want to print the label for each object, you could use a loop or a list comprehension:
But to answer your original question, you need to define the __repr__ method to get the list output right. It could be something as simple as this:
If you want a little more infos in addition of Daniel Roseman answer:
__repr__ and __str__ are two different things in python. (note, however, that if you have defined only __repr__ , a call to class.__str__ will translate into a call to class.__repr__ )
The goal of __repr__ is to be unambiguous. Plus, whenerver possible, you should define repr so that(in your case) eval(repr(instance)) == instance
On the other hand, the goal of __str__ is to be readable; so it matter if you have to print the instance on screen (for the user, probably), if you don’t need to do it, then do not implement it (and again, if str in not implemented will be called repr)
Plus, when type things in the Idle interpreter, it automatically calls the repr representation of your object. Or when you print a list, it calls list.__str__ (which is identical to list.__repr__ ) that calls in his turn the repr representaion of any element the list contains. This explains the behaviour you get and hopefully how to fix it
Как правильно вернуть список экземпляров классов в Python
Как я могу вернуть правильные имена экземпляров класса в моем списке остановок?
4 ответа
Вы смотрите на представление представления repr() для своих классов. repr() вызовет __repr__() если он определен в ваших пользовательских классах:
Правильный способ возврата строкового представления для каждого из ваших экземпляров — определить метод __repr__ в вашем классе, например:
Цель для u и encode(‘utf-8’) состоит в том, чтобы убедиться, что ваш __repr__ не будет ломаться, когда ваш атрибут name установлен в значение Unicode (например, Café Del Mar ). Это обычная ошибка noob, которая обычно не доходит до производства, где она может стать головной болью. Пример использования:
Также обратите внимание, что я подклассифицировал object . Не object подкласса приведет к другому MRO, который вы хотите или ожидаете, и это не соответствует переходу на Python 3.
В качестве альтернативы ответ Martijn, вы можете
Конечно, если вас интересуют только имена экземпляров класса
На основе вывода, который вы предоставляете, вы передаете один экземпляр класса Ligne1Stop . Очевидно, это не даст вам всех «имен» таких случаев.
Что вам нужно сделать, так это сохранить список всех экземпляров класса в этом классе:
Чтобы получить все имена, вам нужно будет добавить способ получения имени и определить метод __unicode__ для использования в качестве строкового представления:
Тогда вы можете сделать:
Вы можете добавить методы, чтобы вернуть отдельную копию списка allinstances если вам нравится и/или скрывать ее за свойством.
A List of Class Objects (Python)
A list of class objects mimics a C array of structures. The snippet explores how to setup the list, and sort the list according to a selected attribute. Then we use a format string to display the sorted list. Take a look at how to search the list. All in all an easy way to handle structured data.

Using python2.4 and I’m getting unexpected results when a dictionary is an element of a class, where all class instances access a single shared hash rather than each class instance having their own separate hash. Modifying the above example. (Apologies if my code formatting is wrong, I haven’t posted before)
I was expecting the first class instance to only have one dictionary entry
<'person0': 0>rather than two dictionary entries. Similar expectation with second
class instance.
How do I create and assign value to separate dictionaries for each class instance?
ee_programmer, I posted the answer in the Python forum so the format is proper.
Thread title: A List of Class Objects

how do I develop a program that calculate class average for each of the three tests for a class of 20 students and the program should also calculate the average of each of the student scores in those three test. Should also display the results in descending order per test i.e a student name and the corresponding test result of the student.
Editor’s note:
There is a difference between a class of students and a Python class. This kind of homework question hardly belongs here. Please start your own properly titled thread in the regular Python forum! Also show some coding effort.

Can u please tell me if this sort of declaration work?
@Shreyaa In principle it works, but it would be written more pythonically this way
For python code, configure your editor to insert 4 space characters for indentation (when you hit the tab key).
Also, if you have more questions, start your own discussion thread instead of reviving old threads !
We’re a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.