Class is not defined despite being imported

52,044

Solution 1

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

Solution 2

import testmodule
# change to
from testmodule import Greeter

or

import testmodule
sayinghi = Greeter("hello world!")
# change to
import testmodule
sayinghi = testmodule.Greeter("hello world!")

You imported the module/package, but you need to reference the class inside it.

You could also do this instead

from testmodule import *

but then beware of namespace pollution

Share:
52,044
Damon Swayn
Author by

Damon Swayn

Computer Science student from Melbourne, Australia with an interest in open source technologies and love to hack on Python, C#, C/C++ and PHP.

Updated on January 21, 2022

Comments

  • Damon Swayn
    Damon Swayn over 2 years

    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?