Import class defined in the same module file?
I have a module file named mymodule.py
that contains the following code:
class foo:
def __init__(self):
self.foo = 1
class bar:
import foo
def __init__(self):
self.bar = foo().foo
A file __init__.py
in the same directory has
from mymodule import foo
From a script in the same directory, I have the following code:
from mymodule import bar
When I try to start bar()
, I get an error No module named foo
. How to instantiate foo
in bar
if they are defined in the same module file?
The classes are first imported with the name of the module. However, you don't need to import the classes in mymodule from within mymodule, just use it. Meaning: Remove import line foo
You don't need to import an object defined in the same module:
class foo:
def __init__(self):
self.foo = 1
class bar:
def __init__(self):
self.bar = foo().foo
The operator is import
intended for objects defined only in other files; you are importing names defined in another python file into the current module.