how to import classes referencing each other in python?

Asked

Viewed 511 times

3

I have a problem when it comes to importing classes into Python. See, there are 4 files:

main:


from classeB import ClasseB

ClasseB()

class A:


from classeModelo import ClasseModelo

class ClasseA():
    Caminho = ""
    modelo = Modelo("","","")
 

model class:


from classeA import ClasseA

class ClasseModelo():
    def __init__(self, v1,v2,v3):
        self.v1 = v1
        self.v2 = v2
        self.v3 = v3

    def carrega(self):
        #Carrega valores nas variáveis da própria classe A
        #a partir do arquivo usando o caminho da classe A
        #open(ClasseA.caminho)
        pass
 

class B:


from classeA import ClasseA

class ClasseB():
    def __init__(self):
        ClasseA.caminho = "caminho no pc"
        ClasseA.modelo.carrega()
 

I need to use the methods of class A in Model Class and vice versa, but when I die he enters a loop infinite.

  • If one depends on the other, one would expect it to loop infinitely, right? The question is: why do both classes depend on the other?

  • 1

    Is this a problem? There may be a problem with your code that is not being presented. You have to be responsible to manage interdependence according to your need. There are no problems in classes depending on each other, there may be problem if you want one object to depend on the other, because it depends on your domain, your problem to solve.

  • I’ll change the question to make it clearer

1 answer

5


First - you are confusing "class" with "modules". In Java, there is a language specificity and public classes must be the only public class in a file of the same name. This has nothing to do with "object orientation" - it’s a Java thing.

In Python, a module is a file with extension . py . In each module we put as many classes as we want, public or not. Independence is even more marked if recommendations for nomenclature are followed: modules must have the name in lowercase, and classes must have the name in Camelcase.

In some cases, depending on the architecture of the project, we may need a "circle reference" - in your question: the Classea, defined in the module_a need to have a reference to the Classeb defined in modulo_b and vice versa.

In this case, as you have well noticed, you cannot put the import commands at the beginning of the file. (Python does not lock or loop as you try to imply in your question - you may have a hard-to-check Nameerror - but if in Python you have a module imported that is "half imported", this is no mistake - if you try to use a name of that module that has not yet been defined at the point where the import is, then you have an error because the name does not exist, and that’s it).

So what you have to keep in mind in these cases is that: (1) The import Python, after the first import of a module, simply creates variables in the local namespace, pointing to the module you ordered imported. (2) The code that is inside the body of a class is executed during import, but the code within the methods of a class is only executed when you create an object of that class. Usually this occurs at a later point in the execution of the program, when the initialization of all modules is complete.

That said, you can perfectly do:

main py.:

import modulo_a, modulo_b

...
obj1 = modulo_a.ClasseA()
...

modulo_a:

...
class ClasseA:
    def __init__(self, ...):
         import modulo_b
         self.objeto_b = modulo_b.ClasseB()

modulo_b:

class B:
    def __init__(self):
         ...
    def cria_a(self):
        import modulo_a
        return modulo_a.ClasseA()

Note that there is no import dependency - and in fact, this code would work well even if the import were at the top in modulo_a and modulo_b.

Now, if I had created a new "A" type object within Classeb’s "init" - that would be another story - object A when created creates an object B, if B creates an A that creates an infinite loop yes: but the problem lies in the logic of that idea, not in the language - if you just try to do a table test and go jotting down the objects that are created when you create an A object that way, you’ll see that you’re trying to create infinite objects - no matter whether in Python, Assembler, C, or Portugol.

  • That’s right, thank you, I’ll take a look. I modified the question a little bit when you were answering me to make it clearer, now you changed the name of the modules a little, but the idea is the same.

Browser other questions tagged

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