Python: How to correctly import one method that depends on another?

Asked

Viewed 6,899 times

3

I’m on the reboot of a project I did in Java, seeking to learn about Python in POO, but I’m stuck on something I haven’t found any solution yet:

I have 2 files ("working.py" and ".py files").

The 2nd is responsible for any file-related services (writing, testing, reading...), all cute within a Files class name.

But when I try to import in any way that works I get an error from some function that was not defined. Since the overwhelming majority of functions inside.py files depends on a name function exists(name).

working.py:

"""==========
  trabalhando.py
=========="""
from arquivos import Arquivos

a = Arquivos()
print(a.le("banco.txt")) #Uma lista do tamanho da qtd de linhas

py files.:

"""==========
  arquivos.py
=========="""
class Arquivos:
    #testes
    def existe (nome): 
        try: 
            with open(nome, "r") as arquivo:
                pass 
        except IOError: 
            return (nome, "w")

        arquivo.close
        return (nome, "a")

    #leitura de arquivo
    def le (arquivo):
        objeto = existe(arquivo)  ##<= linha problema
        if (objeto == (arquivo, "w")):
            return []

        file = open(objeto[0], "r")
        texto = []

        for i in file:
            if (i == "\n"):
                continue
            texto.insert(len(texto), i[:i.index("\n")])
            if (len(texto)%136 == 0):
                print(aguarde(len(texto)))

        file.close
        return texto

So, how do I call le(file) function of.py files without it indicating me problem of "exists is not defined"?

1 answer

3


Functions within classes are called methods, and they must have the value as their first parameter self and after it the parameter that will be passed to the method.

All your methods within the class add the self as first parameter.

After that on the line that gives error is because as you are within the same class the way to call the method that is in the same place (class) is like this:

self.metodo_na_mesma_class(parameters)

Then in your case I’d be:

#leitura de arquivo
def le(self,arquivo):
    objeto = self.existe(arquivo)

Remembering that if the method existe makes an exception in case of error, in the method le should wear a try to capture the generated error.

  • Thanks, I’ve been beating myself up about it since yesterday. Actually my method le(name) depends on the method exists(file) and depended on the wait(). The latter was just to give feedback to the user if there were too many lines. . :)

  • Ahh blz, take a better look at python OO, it has some small details different from java. - Self - Inheritance .. But good luck in your studies.

  • Thanks. I’ll look. I’m studying on Youtube. There are several playlists on the subject and some of them in Portuguese.

Browser other questions tagged

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