pass list of one method to another in python

Asked

Viewed 627 times

1

I have two functions, I need the list of the first to be read by the second, the two are in a view of Django, that each generates a different template.

class Tranfer:
   shared = [] #Essa proprieda sera compartilhada para cada instancia desta 
classe
   def __init__(self, *args):
       self.shared.extend(args)

   def reset(self):
       self.shared = []


def gerar_graficos(request):
    descricao = None
    descricao2 = None

    if request.method=='POST':
        descricao = request.POST['descricao']
        descricao2 = request.POST['descricao2']
    conn = cx_Oracle.connect('banco de dados')
    cur = conn.cursor()

    cur.execute(consulta.format(descricao, descricao2))
    teste = []
    teste2 = []
    teste3 = []
    teste4 = []
    global dados
    global data
    d = 0
    for line in cur:
        teste.extend(line)
    for indice, c in enumerate(teste):
        #if c + 0 == c:
            teste3.extend([c - 10000])
        #else:
            d = 0
    dados = teste3
    cur.execute(consulta.format(descricao, descricao2))
    for coluna in cur:
        teste2.extend(coluna)
    for indice2, c in enumerate(teste2):
        if indice2 >= d:
            teste4.extend([c])
    data = teste4

    transfer = Tranfer()
    transfer.reset()
    transfer.extend(teste3,teste4)

    y_axis = teste3
    x_axis = teste4
    width_n = 0.001
    bar_color = 'yellow'

    cur.close()
    conn.close()

    context = { 'descricao': descricao, 'descricao2': descricao2 }
    return render(request, 'core/graficos_list.html', context)

Pass the test lists 3 and 4 to the function below.

def index(request):
  trans = Tranfer()
  my_list = trans.shared[0]
  my_list2 = trans.shared[1]
  print (my_list)
  fig = Figure()
  ax = fig.add_subplot(1,1,1)
  ax.plot(my_list, my_list2)
  ax.grid()
  buf = io.BytesIO()
  canvas = FigureCanvas(fig)
  canvas.print_png(buf)
  response=HttpResponse(buf.getvalue(), content_type='image/png')
  return (response)
  • Strictly speaking this code has not 2 methods but 2 functions, to be considered "methods" should be members of a class.

  • 1

    For gerar_graficos receive request as a parameter, it seems to me that she is a view of Django. If indeed it is, it seems to me that the functions gerar_graficos and index would be executed on separate HTTP requests and this may be an aggravating in your application since the HTTP protocol, by definition, does not retain status. Anyway the question is rather vague, so I recommend that you edit it and add more details about the problem.

  • I edited as requested

  • So they’re actually executed on separate requests?

  • they are different requests, in fact each one is to be a view, but I put the two in the same

3 answers

0

Just return the 2 elements of the first function and use it in the next function:

def gerar_graficos(request):
    descricao = None
    descricao2 = None
    teste3 = list()
    teste4 = list()
    return (teste3, teste4)

def index(request, graficos):
    fig = Figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot(graficos[0], graficos[1])

result = gerar_graficos(request)
index(request, result)
  • tested your solution gave the following error: index() Missing 1 required positional argument: 'Graphics'

0

Dude you can create a class simply to make this transfer, using the shared class properties, see the example

insira o código aqui
class Tranfer:
    shared = [] #Essa proprieda sera compartilhada para cada instancia desta classe
    def __init__(self, *args):
        self.shared.extend(args)

    def reset(self):
        self.shared = []

#Usando:
lista1 = [1,2,3,4]
lista2 = [5,6,7,8]
a = Tranfer(lista1,lista2) #Primeira instancia passando os valores

b = Tranfer() #segunda instancia mostrando os valores passados pela primeira
print(b.shared) #[[1, 2, 3, 4], [5, 6, 7, 8]]

c = Tranfer() #Terceira instancia com o mesmo resultado
print(c.shared) #[[1, 2, 3, 4], [5, 6, 7, 8]] 

When you want to delete the values just call the reset method. Test there and see if it works, and comments.

  • blz, the class transfers the list values to a variable, but how do I get this variable to be read by the other function? because I have two different functions, I need to transfer the two lists from one function to another, as I do with this Tranfer function?

  • You will just instantiate the class again where you want to retrieve the value, and then access the "Shared" attribute. In the function where you create the lists. 1 - Creates the instance of the transfer class and passes the lists you want to access in the class constructor ja; Myclasstransfer(list1,list2,list3) create an instance of the class without passing parameter and access the Shared parameter, where Voce added the lists lists = Myclasstransfer(). Shared

  • I did as you said, and although there are no more errors, generated a graph zeroed, with no data, so I believe it generated two empty lists

  • Um, are you accessing the lists correctly type. descricao = Tranfer().shared[0] . By logic it should work correctly because the value would be the same for all instances of this class. Then when I was going to ultilizar the value would recover with the code transfer = Transfer()
descricao = transfer.shared[0]
descricao2 = transfer.shared[1]

  • And so Voce would pass it as value for the render context() python
render(request,'seutemplate.html',context={'descricao':descricao, 'descricao2':descricao2})

  • face, I edited the question for the corrected code, and it presents the error "list index out of range". And debugging I saw that the list becomes empty

Show 1 more comment

0

If you want to pass a list within a definition x for a definition y, know that a variable created within a definition, is by default local, I mean, it only works in there.

You can create a global variable and make a copy of your list, that way it becomes available throughout the code. I made an example that gives error and below the solution with a global variable, look at:

# Primeira definição
def definicao_1():
    # Lista
    lista_1 = [1,2,3,4,5,6]

    # Apenas para exibir a lista
    print(lista_1)

# Segunda definição
def definicao_2():
    # Tentativa de exibir a lista criada na definição 1
    print(lista_1)

# Chamada da definição 1 para criar a lista
definicao_1() 
# Chamada da definição 2 para tentar pegar os dados dessa lista
definicao_2()

This code returns this error:

Nameerror: name 'lista_1' is not defined

One of my solutions for this is to create a global variable, which will make a copy of the list in setting 1 and then make it available in setting 2

# Definição 1
def definicao_1():
    # Essa é a nossa lista
    lista_1 = [1,2,3,4,5,6]

    # Vamos criar uma variável global
    global backup

    # A variável global vai receber a lista
    backup = lista_1

    # Apenas o print padrão
    print(lista_1)

# Definição 2
def definicao_2():
    # Vamos tornar a variável backup disponível nessa definição
    global backup

    # Um print para confirmar que deu tudo certo
    print(backup)

# Chamada da definição 1 para criar a lista
definicao_1()
# Chamada da definição 2 para tentar pegar os dados dessa lista
definicao_2()

Here returned this result:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

But of course, there are several other ways, but I think this is the simplest and requires less code change.

  • Cara replicated in my code and error, says that the global variable was not defined, name 'data' is not defined created variable data and date both global and played in the other method as you did, but presents the error

  • They’re in the same file right?

  • Oh and when you do this: "teste1 = ()" You are declaring a tuple and not a list, so use this: "teste1 = []"

  • They’re in the same file, and I declared as test = list() that it’s a list, right? But it still wasn’t

  • Dude when you use () you are creating a tuple, and tuples are immutable. It would be a list if it looked like this: list = []. Take advantage and send the error message that appears

  • not expensive, if to using test = () is a tuple test = list() is a list, but I changed it to how you spoke and gave it anyway, it presents the error: name 'data' is not defined, which was when I passed as global variable

  • I edited the question to show you how the code came to be

  • Before performing the function "index(request)", you are running the function "gerar_graficos(request)" right? Ah and all the content under "index(request)" is with right space?

  • yes, exactly

  • So I have no idea, I’m sorry I can’t help...

  • quiet, thanks for trying

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.