0

Here, I have created two python modules named as test1.py and test2.py.

In test1.py:

class c1: 
    pass

class c2:
    def e(self):
        return c3.x

In test2.py:

from test1 import *

class c3(c1):
    x = 1
    def __init__(self,x):
        self.x = x

class c4(c2):
    def __init__(self,y):
        self.y = y

Now, I need to call these modules using python 3.x interpreter:

$ python
>>> import test2 as t2
>>> import test1 as t1
>>> a = t2.c4(2)
>>> b = t2.c3(4)
>>> a.e()
Traceback (most recent call last):
   File "<stdin>", line1, in <module>
   File "~/test.py", line 6, in e return c3.x
NameError: name 'c3' is not defined

Is there is any way to solve this problem?

Note: If I put those in a single module test.py:

class c1:
    pass

class c2:
    def e(self):
        return c3.x

class c3(c1):
    x = 1
    def __init__(self,x):
        self.x = x

class c4(c2):
     def __init__(self,y):
         self.y = y

If I run it in the interpreter:

$ python
>>> from test import *
>>> a = c4(2)
>>> b = c3(4)
>>> a.e()
1

Solution: Yeah! Finally, this worked for me too.

I did like this:

In test1.py:

import test2

class c1:
    pass

class c2:
    def e(self):
        return test2.c3.x

In test2.py:

from test1 import *

class c3(c1):
    x=1
    def __init__(self,x):
        self.x = x

class c4(c2):
     def __init__(self,y):
          self.y = y

If I run it in Python 3.x interpreter. I need to do this:

$ python
>>> from test2 import *
>>> from test1 import *
>>> a = c4(2)
>>> b = c3(4)
>>> a.e()
1

Warning: Do not do this:

$ python
>>> from test1 import *
Traceback (most recent call last):
...
NameError: name 'c1' is not defined

2 Answers2

0

test1 doesn't know what c3 is.So, you have to import test2 in test1. This can introduce circular dependency in your code.You can read more about circular dependency in python from below links:

Circular (or cyclic) imports in Python

Circular dependency in Python

https://gist.github.com/datagrok/40bf84d5870c41a77dc6

https://micropyramid.com/blog/understand-self-and-init-method-in-python-class/

This is working for me.

import test2 class c1: pass class c2: def e(self): a=test2.c3(4) print a.temp

import test1 class c3(test1.c1): def __init__(self,x): self.temp=x class c4(test1.c2): def __init__(self,y): self.y = y

abhishek627
  • 138
  • 2
  • 10
  • Also, you may want to read this https://stackoverflow.com/questions/30323607/why-do-i-have-to-add-a-blank-init-py-file-to-import-from-subdirectories – abhishek627 Jan 04 '18 at 11:52
0

Class c2 does not know what c3 is, because it is in another .py file. So, you may need to import test2 in test1. This results in circular imports - test1 importing test2 and test2 importing test1.

To fix circular imports, either refactor your program to avoid circular imports or move the imports to the end of the module (like the second way you've done).

Austin
  • 25,759
  • 4
  • 25
  • 48