Inexplicable NameError with command-line Python

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?

Answers


You probably want thing = mystuff.MyStuff() (assuming mystuff is the name of the file where the class MyStuff resides).

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,

import mystuff

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 type mystuff all the time, you can change the name you use to reference it in the current module (file):

import mystuff as ms

now, you can acess MyStuff by:

thing = ms.MyStuff()

And (almost) finally, there's the from mystuff import MyStuff. In this form, you bring MyStuff directly into your namespace, but nothing else from mystuff comes 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 the mystuff file and imports that too.


Need Your Help

How to show sensor output using Dino and Sinatra?

javascript ruby asynchronous sinatra arduino

I would like to show on my page output from one of my sensor(moisture) connected to Arduino.

PHP String Parsing

php regex

I have string which contains something about "amount 3 val 6, amount 7 val 8" and so, what regular expression should I use to get array with corresponding amounts and values?