Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i join list of classes?

I need to get a string out of the list of classes that have .__str__() method.

So potions is a list of objects of a class Potion. Potion __str__ method just returns the name of the potion. I thought of doing something like this

result = "\n".join(potions)

but only string can be joined and i dont know how to call __str__() for each class inside join.

Or i should do somthing like this:

for potion in potions:
    result += "{0}\n".format(potion)

Or may be somthing else?

like image 982
Stals Avatar asked Dec 16 '22 05:12

Stals


1 Answers

result = "\n".join(str(potion) for potion in potions)

That is, using a generator expression (could just as well use a list comprehension too --

result = "\n".join([str(potion) for potion in potions])

to call str() for each potion in potions.

like image 96
AKX Avatar answered Dec 22 '22 00:12

AKX