Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class is not defined despite being imported

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?

like image 823
Damon Swayn Avatar asked May 23 '12 14:05

Damon Swayn


People also ask

Can a class be imported in Python?

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.

What does importing a class do?

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.

What is importlib import_ module?

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.

What is circular import in Python?

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.


1 Answers

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 
like image 104
NPE Avatar answered Oct 02 '22 06:10

NPE