Home > Software engineering >  I can't call a class in subdirectory on Python
I can't call a class in subdirectory on Python

Time:04-04

I can't call a class in other class from a directory above.

I have a code with this directory hierarch:

main.py
|->classprimary.py
|->classec.py
|->classterc.py

In main.py, i call the classterc.py, bellow:

from lib.classprymary import A
from lib.classsec import B
from lib.classterc import C

var = C().list()
print(var)

This code work, when i move main.py to lib directory. But i like clean my code.

CodePudding user response:

import in python allows to load modules.

To create a module you need to add a __init__.py file in your folder.

Should have this hierarchy

main.py
lib/
  __init__.py
  classprimary.py
  classec.py
  classterc.py

CodePudding user response:

The directory structure defined in the question is like this:

main.py
lib/
  classprimary.py
  classec.py
  classterc.py

The call to the modules are correct.

from lib.classprymary import A
from lib.classsec import B
from lib.classterc import C

Without knowing the structure of the calsses and functions inside the library, it appears as though one potential cause of error is from calling the class.

So var = C().list() should become var = C.list().

Here is a good example with a commonly used moule:

from datetime import datetime
t = datetime.time()

Note, in particular, how datetime does not require the parenthasis ( ) as it is not a method, whereas time() does.

However, if you do not notice this error when moving relative path then the cause could be as below.

The other part is that if you are moving main.py into the same directory as the modules, then the imports will change because the lib part of the import is no longer required if the relative path has changed:

from classprymary import A
from classsec import B
from classterc import C
  • Related