I am working my way through the excellent ‘Python The Hard Way’ and copied the following code into a file called mystuff.py:
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
In terminal:
import mystuff
thing = MyStuff()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'MyStuff' is not defined
This has been happening repeatedly with other simple classes today. Can someone tell me what I am doing wrong?
You probably want
thing = mystuff.MyStuff()(assumingmystuffis the name of the file where the classMyStuffresides).The issue here is with how python handles namespaces. You bring something into the current namespace by importing it, but there’s a lot of flexibility in how you merge the namespaces from one file into another. For example,
brings everything from the mystuff (module/file level) namespace into your current namespace, but to access it, you need
mystuff.function_or_class_or_data. If you don’t want to typemystuffall the time, you can change the name you use to reference it in the current module (file):now, you can acess
MyStuffby:And (almost) finally, there’s the
from mystuff import MyStuff. In this form, you bringMyStuffdirectly into your namespace, but nothing else frommystuffcomes into your namespace.Last, (and this one isn’t recommended)
from mystuff import *. This works the same as the previous one, but it also grabs everything else in themystufffile and imports that too.