Skip to content Skip to sidebar Skip to footer

Why Am I Getting Name Error When Importing A Class?

I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents: class Fridge: '''This class im

Solution 1:

No one seems to mention that you can do

from pythontest import Fridge

That way you can now call Fridge() directly in the namespace without importing using the wildcard


Solution 2:

You need to do:

>>> import pythontest
>>> f = pythontest.Fridge()

Bonus: your code would be better written like this:

def __init__(self, items=None):
    """Optionally pass in an initial dictionary of items"""
    if items is None:
         items = {}
    if not isinstance(items, dict):
        raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
    self.items = items

Solution 3:

Try

import pythontest
f=pythontest.Fridge()

When you import pythontest, the variable name pythontest is added to the global namespace and is a reference to the module pythontest. To access objects in the pythontest namespace, you must preface their names with pythontest followed by a period.

import pythontest the preferred way to import modules and access objects within the module.

from pythontest import *

should (almost) always be avoided. The only times when I think it is acceptable is when setting up variables inside a package's __init__, and when working within an interactive session. Among the reasons why from pythontest import * should be avoided is that it makes it difficult to know where variables came from. This makes debugging and maintaining code harder. It also doesn't assist mocking and unit-testing. import pythontest gives pythontest its own namespace. And as the Zen of Python says, "Namespaces are one honking great idea -- let's do more of those!"


Solution 4:

You're supposed to import the names, i.e., either

 import pythontest
 f= pythontest.Fridge()

or,

from pythontest import *
f = Fridge()

Post a Comment for "Why Am I Getting Name Error When Importing A Class?"