Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 361
Rhs Avatar asked Aug 26 '26 15:08

Rhs


1 Answers

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).

like image 94
poke Avatar answered Aug 28 '26 03:08

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!