Rhs
Rhs

Reputation: 3318

Python Idle and Terminal Import Differences

I just started using Python and I have a question about idle vs terminal.

In idle, I made a file called Robot.py

I have a class called Robot

class Robot(object)

    def __init__(self,x,y):
        #some code here etc...

def HelloWorld()
    print "Hello World!"

I have another file called testrobot.py, which looks like so:

import Robot
r = Robot(1,4)

In idle, I am able to successfully create a Robot object when I run testrobot.py. However in terminal, it gives an error Message NameError: Robot is not defined

I'm not sure how to run my program in terminal.

Also:

How can I call my HelloWorld() function which is in Robots.py but not of the class Robot in an external file (such as testrobot.py)?

Thanks in advance!

Upvotes: 3

Views: 2163

Answers (2)

poke
poke

Reputation: 387507

When you load and run scripts in IDLE, they are automatically loaded for the interpreter. That means that as soon as you run the script in IDLE, the Python shell already has those types defined.

When you want to run it from outside of IDLE, i.e. without running the module first, you need to import your Robot from that module. To do that, you import the module, not the type:

import Robot
myRobot = Robot.Robot(...)

Or, if you want to use Robot directly, you need to use the from ... import syntax:

from Robot import Robot
myRobot = Robot(...)

Similarily, you can call your function by using Robot.HelloWorld in the first case, or directly if you add HelloWorld to the import list in the second case:

from Robot import Robot, HelloWorld
myRobot = Robot(...)
HelloWorld()

As you can see, it is generally a good idea to name your files in lower case, as those are the module names (or “namespaces” in other languages).

Upvotes: 2

veiset
veiset

Reputation: 2003

You are trying to create a class of an import, not the class imported.

You are trying to import a file called Robot.py with that import statement. To import your robot class you will have to type import Robot and then write Robot.Robot(1,4) to create an object of it. Alternatively you can import all references from the file: from Robot import * and then write Robot(1,4).

The reason it will work with IDLE is that it basically imports everything from the file you run, allowing you use the methods and classes in that file.

Upvotes: 1

Related Questions