I have the following code:

lista_cosas=[]
class cosa():
    global lista_cosas
    def __init__(self,color):
        self.color=color
    def operacion(self):
        if self.color=="verde":
            lista_cosas.append(cosa("azul"))
        else:
            lista_cosas.append(cosa("verde"))
c=cosa("verde")
lista_cosas.append(c)
n=0
while n<10:
    n+=1
    for cosa in lista_cosas:
        cosa.operacion()

and it gives me the following error:

Traceback (most recent call last):
File "C:/Users/elster/Desktop/Cancer modelling with python/recursive_test.py", line 21, in <module>
cosa.operacion()
File "C:/Users/elster/Desktop/Cancer modelling with python/recursive_test.py", line 9, in operacion
lista_cosas.append(cosa("azul"))
TypeError: 'cosa' object is not callable

I'm using Python 3, what I am doing wrong?

I think it would help if you weren't shadowing the cosa name in your for loop. Classes should use CamelCase, to distinguish them from function names and other stuff. Instantiating a class is like calling a function, so if you are instantiating a Cosa, and not trying to call a Cosa instance (like in the loop), it should work. print(repr(cosa)) should tell you which you are dealing with.

This will never end because you are appending to lista_cosas while iterating over it. I'm not really sure what you were trying to figure out, but this code will run (and create 1024 Cosa's):

lista_cosas=[]
class Cosa():
    def __init__(self,color):
        self.color=color

    def __repr__(self):
        return 'Cosa({!r})'.format(self.color)

    def operacion(self):
        global lista_cosas
        if self.color=="verde":
            lista_cosas.append(Cosa("azul"))
        else:
            lista_cosas.append(Cosa("verde"))
c=Cosa("verde")
lista_cosas.append(c)
print('Initial: {!r}'.format(lista_cosas))
for _ in range(10):
    for cosa in lista_cosas[:]:
        cosa.operacion()

print('After: {!r}'.format(lista_cosas))
print('Length: {}'.format(len(lista_cosas)))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.