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 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 the 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. The import worked successfully, though. There were no errors.
What Is a NameError in Python? In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.
To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
The Python "ImportError: cannot import name" occurs when we have circular imports (importing members between the same files). To solve the error, move the objects to a third file and import them from a central location in other files, or nest one of the imports in a function.
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
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