I seem to have run into a really confusing error. Despite importing the .py file containing my class, Python is insistent that the class doesn't actually exist.
Class definition in testmodule.py:
class Greeter: def __init__(self, arg1=None): self.text = arg1 def say_hi(self): return self.text
main.py:
#!/usr/bin/python import testmodule sayinghi = Greeter("hello world!") print(sayinghi.say_hi())
I have a theory that the import is not working as it should. How do I do this correctly?
Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole way. The import statement consists of the import keyword alongside the name of the module.
Importing classes from other programs allows us to use them within the current program. Thus, helping in improved readability and reusability of code. Importing can be done within the same or from different folders. If you want to learn more about python Programming, visit Python Programming Tutorials.
The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib. __import__() . The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.
Python Circular Imports A circular import occurs when two or more modules depend on each other. In this example, m2.py depends on m1.py and m1.py depends on m2.py . module dependency (Created by Xiaoxu Gao) # m1.py.
Use the fully-qualified name:
sayinghi = testmodule.Greeter("hello world!")
There is an alternative form of import
that would bring Greeter
into your namespace:
from testmodule import Greeter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With