Reputation: 44972
I have a module file called mymodule.py
, which contains the following code:
class foo:
def __init__(self):
self.foo = 1
class bar:
import foo
def __init__(self):
self.bar = foo().foo
The __init__.py
file 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 run bar()
, I get the error that No module named foo
. How can I create an instance of foo
in bar
when they are defined within the same module file?
Upvotes: 3
Views: 5464
Reputation: 1125368
You do not 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 import
statement is intended for objects defined in other files only; you import the names defined in another python file into the current module.
Upvotes: 5
Reputation: 5830
Classes are imported with module name first. However, you don't need to import classes in mymodule from within mymodule, just use it. Meaning: remove the import foo line
Upvotes: 5