Why am I getting an error when importing a class?

I'm just starting to learn Python, but I already have some errors. I created a file called pythontest.py with the following contents:

 class Fridge: """This class implements a fridge where ingredients can be added and removed individually or in groups""" def __init__(self, items={}): """Optionally pass in an initial dictionary of items""" if type(items) != type({}): raise TypeError("Fridge requires a dictionary but was given %s" % type(items)) self.items = items return 

I want to create a new instance of the class in an interactive terminal, so I run the following commands in my terminal: python3

 >> import pythontest >> f = Fridge() 

I get this error:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Fridge' is not defined 

The interactive console cannot find the class I made. However, the import worked successfully. There were no errors.

+4
source share
4 answers

You need to do:

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

Bonus: your code will be better written as follows:

 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 
+4
source

No one seems to mention what you can do

 from pythontest import Fridge 

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

+7
source

Try

 import pythontest f=pythontest.Fridge() 

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

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

 from pythontest import * 

should (almost) always be avoided. The only time I think is acceptable is to set up variables inside the __init__ package and when working in an interactive session. Among the reasons you should avoid from pythontest import * is that it makes it difficult to know where the variables came from. This simplifies code debugging and maintenance. It also does not help mock and test units. import pythontest gives pythontest its own namespace. And as Zen Python says: "Namespaces are one good idea - let more of them!"

+2
source

You must import the names i.e.

  import pythontest f= pythontest.Fridge() 

or,

 from pythontest import * f = Fridge() 
0
source

All Articles