Reuse of functions in Python

1

I am a beginner in programming and I have the following situation:

  • I have a class called TEST. Within this class has the RANDOM function.

  • I have a second class called CHECK. Within this class you have the CHECK function.

  • I want the output of the TEST function to be used in the VERIFY function.

  • In the code below every time I run the VERIFY function, it calls the TEST function again. This brings me to a new value.

  • How do I REUSE the output of the TEST function?

=========

import random

class teste():
    def __init__(self, x = 0):
        self.x = x

def aleatorio(self):
    a = random.randint(0,100)
    return a

class verificar():
    def __init__(self, y = 0):
        self.y = y

    def verifica(self):
        b = teste().aleatorio()
        return b

print (teste().aleatorio())
print (verificar().verifica())

==========

In advance, I thank everyone for their willingness to help.

    
asked by anonymous 16.05.2017 / 15:06

1 answer

1

Do the following:

import random

class teste():
    def __init__(self, x = 0):
        self.x = x
        self.aleatorio()

    def aleatorio(self):
        self.a = random.randint(0,100)
        return self.a

class verificar():
    def __init__(self, y = 0):
        self.y = y

    def verifica(self):
        b = teste()
        return b.a

If you need to call aleatorio() again, you can do the following:

class verificar():
    def __init__(self, y = 0):
        self.y = y
        self.teste = teste()

    def verifica(self, chamar_de_novo = False):
        if (chamar_de_novo):
            self.teste.aleatorio()
        return self.teste.a

Note that here:

print (verificar().verifica())

You are using an object verifica different from here:

print (teste().aleatorio())

That's why the value does not hold. You can, for example, verificar receive a teste object to at least keep the random number generated:

v = verificar()
teste = teste()
teste.aleatorio()
v.teste = teste
    
16.05.2017 / 15:12